Creating DataFrame with Hierarchical Columns

后端 未结 3 1682
迷失自我
迷失自我 2020-12-31 13:53

What is the easiest way to create a DataFrame with hierarchical columns?

I am currently creating a DataFrame from a dict of names -> Series

3条回答
  •  悲&欢浪女
    2020-12-31 14:35

    I know the question is really old but for pandas version 0.19.1 one can use direct dict-initialization:

    d = {('a','b'):[1,2,3,4], ('a','c'):[5,6,7,8]}
    df = pd.DataFrame(d, index=['r1','r2','r3','r4'])
    df.columns.names = ('l1','l2')
    print df
    
    l1  a   
    l2  b  c
    r1  1  5
    r2  2  6
    r3  3  7
    r4  4  8
    

提交回复
热议问题