Pandas - How to flatten a hierarchical index in columns

后端 未结 17 1349
忘掉有多难
忘掉有多难 2020-11-22 02:55

I have a data frame with a hierarchical index in axis 1 (columns) (from a groupby.agg operation):

     USAF   WBAN  year  month  day  s_PC  s_CL         


        
17条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 03:13

    In case you want to have a separator in the name between levels, this function works well.

    def flattenHierarchicalCol(col,sep = '_'):
        if not type(col) is tuple:
            return col
        else:
            new_col = ''
            for leveli,level in enumerate(col):
                if not level == '':
                    if not leveli == 0:
                        new_col += sep
                    new_col += level
            return new_col
    
    df.columns = df.columns.map(flattenHierarchicalCol)
    

提交回复
热议问题