Reset a column's MultiIndex levels

后端 未结 3 1170
忘了有多久
忘了有多久 2020-12-14 01:14

Is there a shorter way of dropping a column MultiIndex level (in my case, basic_amt) except transposing it twice?

In [704]: test
Out[704]: 
             


        
3条回答
  •  时光说笑
    2020-12-14 01:44

    Zip levels together

    Here is an alternative solution which zips the levels together and joins them with underscore.

    Derived from the above answer, and this was what I wanted to do when I found this answer. Thought I would share even if it does not answer the exact above question.

    ["_".join(pair) for pair in df.columns]
    

    gives

    ['basic_amt_NSW', 'basic_amt_QLD', 'basic_amt_VIC', 'basic_amt_All']
    

    Just set this as a the columns

    df.columns = ["_".join(pair) for pair in df.columns]
    
               basic_amt_NSW  basic_amt_QLD  basic_amt_VIC  basic_amt_All
    Faculty                                                              
    All                    1              1              2              4
    Full Time              0              1              0              1
    Part Time              1              0              2              3
    

提交回复
热议问题