使用 Pandas 从具有不同行长度的文件导入数据

Import data from file with different row length using Pandas

我有一个包含一定数量行的 txt 文件。 每行可能包含不同数量的项目。

这是 input.txt 的示例:

1,0,50,20,2,96,152,65,32,0
1,0,20,50,88,45,151
1,1,90,15,86,11,158,365,45
2,0,50,20,12,36,157,25
2,0,20,50,21,63,156,76,32,77
3,1,50,20,78,48,152,75,52,22,96

我的目标是将此数据存储在具有以下结构的数据框中:

因此输出应该是这样的:

Out[8]: 
   A  B   C   D                              E
0  1  0  50  20        [2, 96, 152, 65, 32, 0]
1  1  0  20  50                  [88, 45, 151]
2  1  1  90  15         [86, 11, 158, 365, 45]
3  2  0  50  20              [12, 36, 157, 25]
4  2  0  20  50      [21, 63, 156, 76, 32, 77]
5  3  1  50  20  [78, 48, 152, 75, 52, 22, 96]

我尝试使用 pandas.read_csv('input.txt') 但它不起作用,因为行的长度不同。

你能建议我一个聪明而优雅的方法来实现我的目标吗?

您可以将 read_csv 与一些不在数据中的分隔符一起使用 - 输出是一列 df:

import pandas as pd
from pandas.compat import StringIO

temp="""1,0,50,20,2,96,152,65,32,0
1,0,20,50,88,45,151
1,1,90,15,86,11,158,365,45
2,0,50,20,12,36,157,25
2,0,20,50,21,63,156,76,32,77
3,1,50,20,78,48,152,75,52,22,96"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp), sep="|", names=['A'])
print (df)
                                 A
0       1,0,50,20,2,96,152,65,32,0
1              1,0,20,50,88,45,151
2       1,1,90,15,86,11,158,365,45
3           2,0,50,20,12,36,157,25
4     2,0,20,50,21,63,156,76,32,77
5  3,1,50,20,78,48,152,75,52,22,96

然后使用split:

cols = list('ABCDE')
df[cols] = df.A.str.split(',', n=4, expand=True)
df.E = df.E.str.split(',')
print (df)
   A  B   C   D                              E
0  1  0  50  20        [2, 96, 152, 65, 32, 0]
1  1  0  20  50                  [88, 45, 151]
2  1  1  90  15         [86, 11, 158, 365, 45]
3  2  0  50  20              [12, 36, 157, 25]
4  2  0  20  50      [21, 63, 156, 76, 32, 77]
5  3  1  50  20  [78, 48, 152, 75, 52, 22, 96]