我有这个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
和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]
如果需要混合数据 - 带标量的list
s仅为Series.mask
检查的[
开始的值添加Series.str.startswith
for apply solution:
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