如何将DataFrame的2级列索引合并为单个列索引?

时间:2018-02-11 06:09:00

标签: python pandas data-analysis

我有一个像下面那样有2级列索引的DataFrame,现在我必须将它组合成单级列索引,模式如“Level1_Level2”

        CNT_LOAN                        CNT_RCHG            
month   201605  201606  201607  201608  201609  201610  201605
id                                  
800008184   6     4       4       4        6       9      18    
800008588  NaN   NaN     NaN      0       NaN     NaN     NaN   
800011836   12    13      24      19      12      17      24    
800018523   4     1       5       4       0       4       9 
800024880   3     6       3       4       8       5       10

2 个答案:

答案 0 :(得分:1)

使用list comprehension

df.columns = ['{}_{}'.format(x, y) for x, y in df.columns]
print (df)
           CNT_LOAN_201605  CNT_LOAN_201606  CNT_LOAN_201607  CNT_LOAN_201608  \
id                                                                              
800008184              6.0              4.0              4.0                4   
800008588              NaN              NaN              NaN                0   
800011836             12.0             13.0             24.0               19   
800018523              4.0              1.0              5.0                4   
800024880              3.0              6.0              3.0                4   

           CNT_RCHG_201609  CNT_RCHG_201610  CNT_RCHG_201605  
id                                                            
800008184              6.0              9.0             18.0  
800008588              NaN              NaN              NaN  
800011836             12.0             17.0             24.0  
800018523              0.0              4.0              9.0  
800024880              8.0              5.0             10.0  

但如果两个级别都是字符串:

df.columns = df.columns.map('_'.join)

答案 1 :(得分:0)

您可以使用地图,通知map('_'.join)仅适用于str,如果是数字则无法使用

df.columns = df.columns.map('{0[0]}_{0[1]}'.format)