我使用Pandas导入了CSV,并使用字符串条目读入了一列.检查本系列(列)的条目,我发现它们实际上应该是列表.例如:
df['A'] = pd.Series(['["entry11"]', '["entry21","entry22"]', '["entry31","entry32"]'])
Run Code Online (Sandbox Code Playgroud)
我想从字符串中提取列表元素.到目前为止,我已经尝试了以下链:
df['A'] = df['A'].replace("'",'',regex=True).
replace('\[','',regex=True).
replace('\]','',regex=True).
str.split(",")
Run Code Online (Sandbox Code Playgroud)
(当然,所有在一条线上).
这让我在一列中找回了我想要的列表元素.
我的问题:有没有更有效的方法呢?对于应该更容易一些的东西来说,这似乎很紧张.
你可以"应用"将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]
Run Code Online (Sandbox Code Playgroud)
也有map()和applymap()-这里是讨论其不同之话题: