将 pd 数据框转换为列表

Convert pd dataframe into list

我有这个 txt 输入:

["A" "B" "C" "D"]
[8 3 6 11]
[5 7 4 3]
14

我使用以下方式读取文件:

df = pd.read_csv("data.txt", header = None, engine = 'python')

然后,我想将此数据框转换为列表。 我试过这样做:

L = df[0].iloc[0]
>>> '["A" "B" "C" "D"]'

但是,如果我想得到第一个值,输出是

L[0]

>>> '['

我已经试过了

ast.literal_eval(L)

没有成功。我得到:

['ABCD']

有什么建议吗? 谢谢!

您可以使用 Series.str.strip with Series.str.split:

df['new'] = df[0].str.strip('[]').str.split()
print (df)
                   0                   new
0  ["A" "B" "C" "D"]  ["A", "B", "C", "D"]
1         [8 3 6 11]         [8, 3, 6, 11]
2          [5 7 4 3]          [5, 7, 4, 3]
3                 14                  [14]

如果需要混合数据 - lists with scalar(s) 添加 Series.mask for apply solution only for values starting by [ checked by Series.str.startswith:

df['new'] = df[0].mask(df[0].str.startswith('['), df[0].str.strip('[]').str.split())
print (df)
                   0                   new
0  ["A" "B" "C" "D"]  ["A", "B", "C", "D"]
1         [8 3 6 11]         [8, 3, 6, 11]
2          [5 7 4 3]          [5, 7, 4, 3]
3                 14                    14