[英]How do I extract the list inside a string in Python?
I imported a CSV using Pandas and one column was read in with string entries. 我使用Pandas导入了CSV,并使用字符串条目读入了一列。 Examining the entries for this Series (column), I see that they should actually be lists.
检查本系列(列)的条目,我发现它们实际上应该是列表。 For example:
例如:
df['A'] = pd.Series(['["entry11"]', '["entry21","entry22"]', '["entry31","entry32"]'])
I would like to extract the list elements from the strings. 我想从字符串中提取列表元素。 So far, I've 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 gives me back my desired list elements in one column. 这让我在一列中找回了我想要的列表元素。
My question: Is there a more efficient way of doing this? 我的问题:有没有更有效的方法呢? This seems like a lot of strain for something that should be a little easier.
对于应该更容易一些的东西来说,这似乎很紧张。
You can "apply" the ast.literal_eval()
to the series: 您可以将
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]
There is also map()
and applymap()
- here is a topic where the differences are discussed: 还有
map()
和applymap()
- 这是讨论差异的主题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.