Python 我需要从一个包含列表的字典中创建一个带有多索引的熊猫数据框

Python 我需要从一个包含列表的字典中创建一个带有多索引的熊猫数据框,python,pandas,dictionary,dataframe,multi-index,Python,Pandas,Dictionary,Dataframe,Multi Index,好的,我有这本字典: {'a': [{'foo': '1'}, {'bar': '30'}], 'b': [{'foo': '3'}], 'c': [{'foo': '184'}, {'bar': '25'}], 'd': [{'foo': '6'}], 'e': [{'bar': '4'}], 'f': [{'foo': '12'},{'bar': '1'}], 'name': 'brian'} 我想将其转换为具有多重索引的数据帧,如下所示: a

好的,我有这本字典:

 {'a': [{'foo': '1'}, {'bar': '30'}],
 'b': [{'foo': '3'}],
 'c': [{'foo': '184'}, {'bar': '25'}],
 'd': [{'foo': '6'}],
 'e': [{'bar': '4'}],
 'f': [{'foo': '12'},{'bar': '1'}],
'name': 'brian'}
我想将其转换为具有多重索引的数据帧,如下所示:

            a        b        c       d          e         f
         foo bar  foo bar  foo bar  foo bar    foo bar   foo bar
  brian  1   30    3   0   184  25   6   0     0    4     12   1
        a       b   c        d   e   f    
      bar foo foo bar  foo foo bar bar foo
brian  30   1   3  25  184   6   4   1  12

有什么帮助吗?

我猜您会有一堆这样的dict,其中每个名称都应该作为数据帧的索引。在这种情况下,您可以执行以下操作:

1.检索名称并从dict原始dict中删除:

name = my_dict['name']
del my_dict['name']
2.将您的dict转换为合适的形状:

 my_dict_exploded = {(k,innerk):innerv for k,v in my_dict.items() for element in v for innerk,innerv in element.items()}
数据帧(my_dict_分解,索引=[name])

您的数据帧将如下所示:

            a        b        c       d          e         f
         foo bar  foo bar  foo bar  foo bar    foo bar   foo bar
  brian  1   30    3   0   184  25   6   0     0    4     12   1
        a       b   c        d   e   f    
      bar foo foo bar  foo foo bar bar foo
brian  30   1   3  25  184   6   4   1  12
这类似于另一篇帖子:@BrenBarn的答案非常有用