How to extract a list inside a string in Python?

I imported CSV using Pandas and one column was read with string rows. Studying the entries for this series (column), I see that they should be lists. For instance:

df['A'] = pd.Series(['["entry11"]', '["entry21","entry22"]', '["entry31","entry32"]'])

I would like to extract list items from strings. So far I have tried the following chain:

df['A'] = df['A'].replace("'",'',regex=True).
                  replace('\[','',regex=True).
                  replace('\]','',regex=True).
                  str.split(",")

(all on one line, of course).

and this returns me the list items in one column.

  • ['"entry11"']
  • ['"entry21", "entry22"']
  • ['"entry31", "entry32"']

My question is: is there a more efficient way to do this? It seems very stressful for something that should be a little easier.

+4
source share
1 answer

"" ast.literal_eval() :

In [8]: from ast import literal_eval

In [9]: df['A'] = df['A'].apply(literal_eval)

In [10]: df
Out[10]: 
                    A
0           [entry11]
1  [entry21, entry22]
2  [entry31, entry32]

map() applymap() - , :

+6

Source: https://habr.com/ru/post/1668316/


All Articles