我得到了一个相当大的 Excel 文件(5k 行),也是一个 CSV 文件,我想将其制作成 pandas 多级 DataFame。该文件的结构如下:
SampleID OtherInfo Measurements Error Notes
sample1 stuff more stuff
36 6
26 7
37 8
sample2 newstuff lots of stuff
25 6
27 7
其中测量次数是可变的(有时为零)。任何信息之间都没有完整的空白行,并且在具有其他(字符串)数据的行上,“测量”和“错误”列为空;这可能会使解析变得更加困难(?)。有没有一种简单的方法可以自动执行此转换?我最初的想法是先用 Python 解析文件,然后循环将内容送入 DataFrame 插槽,但我不知 Prop 体如何实现它,或者这是否是最佳行动方案。
提前致谢!
最佳答案
看起来您的文件具有固定宽度的列,对此可以使用 read_fwf()。
In [145]: data = """\
SampleID OtherInfo Measurements Error Notes
sample1 stuff more stuff
36 6
26 7
37 8
sample2 newstuff lots of stuff
25 6
27 7
"""
In [146]: df = pandas.read_fwf(StringIO(data), widths=[12, 13, 14, 9, 15])
好的,现在我们有了数据,只需做一些额外的工作,您就有了一个框架,您可以在该框架上使用 set_index() 创建多级索引。
In [147]: df[['Measurements', 'Error']] = df[['Measurements', 'Error']].shift(-1)
In [148]: df[['SampleID', 'OtherInfo', 'Notes']] = df[['SampleID', 'OtherInfo', 'Notes']].fillna()
In [150]: df = df.dropna()
In [151]: df
Out[151]:
SampleID OtherInfo Measurements Error Notes
0 sample1 stuff 36 6 more stuff
1 sample1 stuff 26 7 more stuff
2 sample1 stuff 37 8 more stuff
4 sample2 newstuff 25 6 lots of stuff
5 sample2 newstuff 27 7 lots of stuff
关于python - 将 excel 或 csv 文件转换为 pandas 多级数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12576313/