Pandas: Multilevel column names

前端 未结 5 1121
梦毁少年i
梦毁少年i 2020-12-08 02:28

pandas has support for multi-level column names:

>>>  x = pd.DataFrame({\'instance\':[\'first\',\'first\',\'first\'],\'foo\':[\'a\',\'b         


        
5条回答
  •  北海茫月
    2020-12-08 03:00

    A lot of these solutions seem just a bit more complex than they need to be.

    I prefer to make things look as simple and intuitive as possible when speed isn't absolutely necessary. I think this solution accomplishes that. Tested in versions of pandas as early as 0.22.0.

    Simply create a DataFrame (ignore columns in the first step) and then set colums equal to your n-dim list of column names.

    In [1]: import pandas as pd                                                                                                                                                                                          
    
    In [2]: df = pd.DataFrame([[1, 1, 1, 1], [2, 2, 2, 2]])                                                                                                                                                              
    
    In [3]: df                                                                                                                                                                                                           
    Out[3]: 
       0  1  2  3
    0  1  1  1  1
    1  2  2  2  2
    
    In [4]: df.columns = [['a', 'c', 'e', 'g'], ['b', 'd', 'f', 'h']]                                                                                                                                                    
    
    In [5]: df                                                                                                                                                                                                           
    Out[5]: 
       a  c  e  g
       b  d  f  h
    0  1  1  1  1
    1  2  2  2  2
    

提交回复
热议问题