Read multi-index on the columns from csv file

后端 未结 2 2101
萌比男神i
萌比男神i 2020-12-14 01:42

I have a .csv file that looks like this:

Male, Male, Male, Female, Female
R, R, L, R, R
.86, .67, .88, .78, .81

I want to read that into a

2条回答
  •  失恋的感觉
    2020-12-14 02:09

    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]
    

提交回复
热议问题