如何修复不平衡的列MultiIndex?

时间:2018-10-18 08:17:42

标签: python pandas

我尝试读入一些结构不佳的csv文件:

[empty], A, A, B, B
time   , X, Y, X, Y
0.0    , 0, 0, 0, 0
1.0    , 2, 5, 7, 0
...    , ., ., ., .

pandas.read_csvheader=[0,1]参数一起使用,可以很好地访问值:

>>> df = pd.read_csv('file.csv', header=[0,1]'
>>> df.A.X
0 0
1 2
...

但是时间标题上方的空白字段会导致丑陋的Unnamed: 0_level_0级别:

>>> df.columns
MultiIndex(levels=[['Unnamed: 0_level_0', 'A', 'B'], ...

有什么办法可以解决此问题,因此我可以再次使用df.Time访问时间数据吗?

修改

这是真实数据集的摘要:

,,Bone,Bone,Bone
,,Skeleton1_Hip,Skeleton1_Hip,Skeleton1_Hip
,,"1","1","1"
,,Rotation,Rotation,Rotation
Frame,Time,X,Y,Z
0,0.000000,0.009332,0.999247,0.021044
1,0.008333,0.009572,0.999217,0.020468
3,0.016667,0.009871,0.999183,0.019797

(有关更完整的示例,另请参见:https://gist.github.com/fhaust/25ba612f99420d366f0597b15dbf43e7

阅读方式:

pd.read_csv(file, skiprows=2, header=[0,1,3,4], index_col=[1])

我不太在意Frame列,因为它是与行索引隐式给出的。

1 个答案:

答案 0 :(得分:1)

添加参数index_col以将第一列转换为index

import pandas as pd

temp=u""",A,A,B,B
time,X,Y,X,Y
0.0,0,0,0,0
1.0,2,5,7,0"""
#after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
df = pd.read_csv(pd.compat.StringIO(temp), header=[0,1], index_col=[0])

print (df)
      A     B   
time  X  Y  X  Y
0.0   0  0  0  0
1.0   2  5  7  0

或重命名列:

df = df.rename(columns={'Unnamed: 0_level_0':'val'})
print (df)
   val  A     B   
  time  X  Y  X  Y
0  0.0  0  0  0  0
1  1.0  2  5  7  0