[英]Create a list of lists stored as objects in a single column
I have lists stored as objects in a column of data. 我将列表作为对象存储在数据列中。 I need to create a single list from these 'lists' but they are not being recognized as a list. 我需要从这些“列表”中创建一个列表,但无法将它们识别为列表。
I have tried converting column to a list, concatenating, creating a series but the results are not treated as a list. 我曾尝试将列转换为列表,进行串联,创建系列,但结果未视为列表。
What I have: 我有的:
code1
Out[83]:
0 ['hair', 'body']
1 ['hair', 'body']
2 ['hair', 'body']
Name: personal_interests, dtype: object
code1.tolist()
Out[79]: ["['hair', 'body']", "['hair', 'body']", "['hair', 'body']"]
What I need: 我需要的:
example = [['hair', 'body'],
['hair', 'body'],
['hair', 'body']]
example
Out[94]: [['hair', 'body'], ['hair', 'body'], ['hair', 'body']]
The following solution evaluates the list inside the string and appends to a new empty list: 以下解决方案评估字符串中的列表,并将其追加到新的空列表中:
from ast import literal_eval
l1 = ["['hair', 'body']", "['hair', 'body']", "['hair', 'body']"]
l2 = []
for i in l1:
l2.append(literal_eval(i))
l2
#[['hair', 'body'], ['hair', 'body'], ['hair', 'body']]
I tried to reproduce the problem by passing the lists as strings instead of pure lists: 我试图通过将列表作为字符串而不是纯列表传递来重现该问题:
df= pd.DataFrame({'a':["['hair', 'body']", "['hair', 'body']"]})
df
a
0 ['hair', 'body']
1 ['hair', 'body']
As you will notice, the elements in the dataframe do not show as strings but as normal lists. 您将注意到,数据框中的元素不会显示为字符串,而是显示为普通列表。 When I convert the series to list, the elements are represented as strings, as expected: 当我将系列转换为列表时,元素将按预期方式以字符串表示:
df['a'].tolist()
#["['hair', 'body']", "['hair', 'body']"]
So now if we apply
literal_eval on all elements and then convert to list, we get the desired results. 所以现在,如果我们对所有元素apply
literal_eval,然后转换为列表,我们将获得所需的结果。
df['a'].apply(literal_eval).tolist()
#[['hair', 'body'], ['hair', 'body']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.