将excel或csv文件转换为pandas多级数据帧

cos*_*tot 5 python csv excel dataframe pandas

我已经获得了一个相当大的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
Run Code Online (Sandbox Code Playgroud)

其中测量数量是可变的(有时为零).任何信息之间没有完整的空行,并且"测量"和"错误"列在具有其他(字符串)数据的行上为空; 这可能会使解析更难(?).是否有一种简单的方法可以自动执行此转换?我最初的想法是首先使用Python解析文件,然后在循环中将内容提供到DataFrame插槽中,但我不确切知道如何实现它,或者它是否是最佳的行动方案.

提前致谢!

Wou*_*ire 5

看起来您的文件具有固定宽度的列,可以使用 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])
Run Code Online (Sandbox Code Playgroud)

好的,现在我们有了数据,只需一点额外的工作,您就拥有了一个可以使用 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
Run Code Online (Sandbox Code Playgroud)