Pandas - How to flatten a hierarchical index in columns

后端 未结 17 1078
忘掉有多难
忘掉有多难 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:23

    The most pythonic way to do this to use map function.

    df.columns = df.columns.map(' '.join).str.strip()
    

    Output print(df.columns):

    Index(['USAF', 'WBAN', 'day', 'month', 's_CD sum', 's_CL sum', 's_CNT sum',
           's_PC sum', 'tempf amax', 'tempf amin', 'year'],
          dtype='object')
    

    Update using Python 3.6+ with f string:

    df.columns = [f'{f} {s}' if s != '' else f'{f}' 
                  for f, s in df.columns]
    
    print(df.columns)
    

    Output:

    Index(['USAF', 'WBAN', 'day', 'month', 's_CD sum', 's_CL sum', 's_CNT sum',
           's_PC sum', 'tempf amax', 'tempf amin', 'year'],
          dtype='object')
    

提交回复
热议问题