Setting DataFrame column headers to a MultiIndex

后端 未结 1 1561
粉色の甜心
粉色の甜心 2020-12-31 03:44

How do I convert an existing dataframe with single-level columns to have hierarchical index columns (MultiIndex)?

Example dataframe:



        
相关标签:
1条回答
  • 2020-12-31 04:11

    You were close, just set the columns directly to a new (equal sized) index-like (which if its a list-of-list will convert to a multi-index)

    In [8]: df
    Out[8]: 
       one  two  three
    A    0    1      2
    B    3    4      5
    
    In [10]: df.columns = [['odd','even','odd'],df.columns]
    
    In [11]: df
    Out[11]: 
       odd  even    odd
       one   two  three
    A    0     1      2
    B    3     4      5
    

    Reindex will reorder / filter the existing index. The reason you get all nans is you are saying, hey find the existing columns that match this new index; none match, so that's what you get

    0 讨论(0)
提交回复
热议问题