如何从带有列表的嵌套字典中构建MultiIndex Pandas DataFrame [英] How to build a MultiIndex Pandas DataFrame from a nested dictionary with lists

查看:140
本文介绍了如何从带有列表的嵌套字典中构建MultiIndex Pandas DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字典.

d= {'key1': {'sub-key1': ['a','b','c','d','e']},
    'key2': {'sub-key2': ['1','2','3','5','8','9','10']}}

帖子的帮助下,我成功地完成了将该字典成功转换为DataFrame.

With the help of this post, I managed to successfully convert this dictionary to a DataFrame.

df = pd.DataFrame.from_dict({(i,j): d[i][j] 
                            for i in d.keys() 
                            for j in d[i].keys()},
                            orient='index')

但是,我的DataFrame采用以下形式:

However, my DataFrame takes the following form:

                  0  1  2  3  4     5     6
(key1, sub-key1)  a  b  c  d  e  None  None
(key2, sub-key2)  1  2  3  5  8     9    10

我可以使用元组作为索引值,但是我认为使用多级DataFrame更好. 之类的帖子已帮助我在其中创建分两个步骤进行,但是我却很难在一个步骤中完成(即从最初创建开始),因为字典中的列表以及随后的元组都增加了一定程度的复杂性.

I can work with tuples, as index values, however I think it's better to work with a multilevel DataFrame. Post such as this one have helped me to create it in two steps, however I am struggling to do it in one step (i.e. from the initial creation), as the list within the dictionary as well as the tuples afterwards are adding a level of complication.

推荐答案

我认为您很亲密,因为可能使用MultiIndex

I think you are close, for MultiIndex is possible used MultiIndex.from_tuples method:

d = {(i,j): d[i][j] 
       for i in d.keys() 
       for j in d[i].keys()}

mux = pd.MultiIndex.from_tuples(d.keys())
df = pd.DataFrame(list(d.values()), index=mux)
print (df)
               0  1  2  3  4     5     6
key1 sub-key1  a  b  c  d  e  None  None
key2 sub-key2  1  2  3  5  8     9    10

谢谢, 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆