pandas 如何用python组合一列的字符串列表来创建一个列表的列表?

col17t5w  于 2022-11-05  发布在  Python
关注(0)|答案(4)|浏览(144)

我的数据集中有一列字符串列表,如下所示:
立柱
[“平板电脑”、“手机”、“人”]
['人','屋']

['人','计算机']
['计算机','膝上型计算机']
如何获得包含此列元素的列表列表?我希望输出如下:
[[“平板电脑”、“手机”、“人”]、[“人”、“房子”]、. . . .. .、[“人”、“电脑”]、[“电脑”、“笔记本电脑”]]

vfh0ocws

vfh0ocws1#

使用ast.literal_eval转换列表解析中的字符串列表:

import ast

L = [ast.literal_eval(x) for x in df["column"]]
print (L)
[['tablet', 'mobile', 'man'], ['people', 'house'], 
 ['people', 'computer'], ['computer', 'laptop']]
62o28rlo

62o28rlo2#

import pandas as pd

result_list = []

df = pd.read_csv("file_name")
series_1 = df.loc[::, "column_name"]

for s in series_1:
    result_list.append(s)

print(result_list)
ccrfmcuu

ccrfmcuu3#

如果你df就像

column
0  ['tablet', 'mobile, man']
1        ['people', 'house']
2      ['people, 'computer']
3     ['computer', 'laptop']

您可以通过使用tolist()调用列来获取列表

df["column"].tolist()

输出量:

[['tablet', 'mobile', 'man'], ['people', 'house'], ['people', 'computer'], ['computer', 'laptop']]
kxkpmulp

kxkpmulp4#

import pandas as pd

result_list = []

df = pd.read_csv("file_name")
series_1 = df.loc[::, "column_name"]

for s in series_1:
    list1 = s.strip("[]").replace(" ", "").replace("'", "").split(",")
    result_list.append(s)

print(result_list)

相关问题