简体   繁体   English

如何在Python中提取字符串中的列表?

[英]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. 这让我在一列中找回了我想要的列表元素。

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

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.

相关问题 如果列表中的项目在 python 中有某个字符串,我该如何提取它? - How do I extract an item in a list if it has a certain string in python? 如何从 python 中的列表中提取? - How do I extract from a list in python? 如何在Python字符串中提取字典? - How do I extract a dictionary in a Python string? 在python中,如何通过匹配原始列表中的字符串模式从字符串列表中提取子列表 - In python, how do i extract a sublist from a list of strings by matching a string pattern in the original list Python:如何将列表内的字符串转换为列表内的json,同时保留双引号 - Python: How do I convert a string inside a list to a json inside a list whilst retaining the double quotes 如何在python中提取嵌套的json名称并转换为点符号字符串列表? - How do I extract nested json names and convert to dot notation string list in python? 如何从Python中的长字符串中提取一些字符串? - How do I extract some string from a long string in Python? 我如何使用正则表达式python提取引号内的值? - how do i extract value inside quotes using regex python? 如何在python中的字符串中提取字符串? - How to extract string inside a string in python? 如何从 PYTHON I 中以“A”开头的列表中提取单词? - How do I extract words from a list that start with “A” in PYTHON I?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM