Read multi-index on the columns from csv file

六眼飞鱼酱① 提交于 2019-11-30 03:18:44

I think the problem is that you have duplicated columns: two ( Female, R).

Not sure whether it's a bug or the duplicated columns are unacceptable. Here's a workaround for you:

First read the csv with tupleize_cols=True

In [61]: df = pd.read_csv('test.csv', header=[0, 1], skipinitialspace=True, tupleize_cols=True)

In [62]: df
Out[62]: 
   (Male, R)  (Male, R)  (Male, L)  (Female, R)  (Female, R)
0       0.67       0.67       0.88         0.81         0.81

[1 rows x 5 columns]

Then convert the type of the column from Index to MultiIndex

In [63]: df.columns = pd.MultiIndex.from_tuples(df.columns)

In [64]: df
Out[64]: 
   Male              Female      
      R     R     L       R     R
0  0.67  0.67  0.88    0.81  0.81

[1 rows x 5 columns]

As of version 0.21 of pandas, MultiIndexes are created by default so df = pd.read_csv('file.csv', header=[0,1]) should do the job.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!