DataFrame with MultiIndex to dict

后端 未结 1 1683
别跟我提以往
别跟我提以往 2020-12-09 11:33

I have a dataframe with a MultiIndex. I am wondering whether I created the data frame in the correct manner (see below).

             01.01  02.01  03.01  04         


        
1条回答
  •  时光说笑
    2020-12-09 12:14

    For converting whole dataframe to dictionary Try:

    df.groupby(level=0).apply(lambda df: df.xs(df.name).to_dict()).to_dict()
    
    {'bar': {'01.01': {'total1': 40, 'total2': 36},
      '02.01': {'total1': 52, 'total2': 85},
      '03.01': {'total1': 18, 'total2': 5},
      '04.01': {'total1': 11, 'total2': 92}},
     'baz': {'01.01': {'total1': 23, 'total2': 50},
      '02.01': {'total1': 39, 'total2': 49},
      '03.01': {'total1': 45, 'total2': 51},
      '04.01': {'total1': 70, 'total2': 65}},
     'foo': {'01.01': {'total1': 23, 'total2': 64},
      '02.01': {'total1': 97, 'total2': 56},
      '03.01': {'total1': 17, 'total2': 94},
      '04.01': {'total1': 97, 'total2': 45}},
     'qux': {'01.01': {'total1': 13, 'total2': 80},
      '02.01': {'total1': 73, 'total2': 8},
      '03.01': {'total1': 38, 'total2': 61},
      '04.01': {'total1': 4, 'total2': 50}}}
    

    For converting one particular column, select before converting it to dictionary i.e

    df.groupby(level=0).apply(lambda df: df.xs(df.name)[colname].to_dict()).to_dict()
    

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