Pandas - How to flatten a hierarchical index in columns

后端 未结 17 1104
忘掉有多难
忘掉有多难 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条回答
  •  旧时难觅i
    2020-11-22 03:22

    I think the easiest way to do this would be to set the columns to the top level:

    df.columns = df.columns.get_level_values(0)
    

    Note: if the to level has a name you can also access it by this, rather than 0.

    .

    If you want to combine/join your MultiIndex into one Index (assuming you have just string entries in your columns) you could:

    df.columns = [' '.join(col).strip() for col in df.columns.values]
    

    Note: we must strip the whitespace for when there is no second index.

    In [11]: [' '.join(col).strip() for col in df.columns.values]
    Out[11]: 
    ['USAF',
     'WBAN',
     'day',
     'month',
     's_CD sum',
     's_CL sum',
     's_CNT sum',
     's_PC sum',
     'tempf amax',
     'tempf amin',
     'year']
    

提交回复
热议问题