简体   繁体   English

如何使用列表从嵌套字典构建MultiIndex Pandas DataFrame

[英]How to build a MultiIndex Pandas DataFrame from a nested dictionary with lists

I have the following dictionary. 我有以下字典。

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

With the help of this post, I managed to successfully convert this dictionary to a DataFrame. 这篇文章的帮助下,我成功地将这个字典转换为DataFrame。

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

However, my DataFrame takes the following form: 但是,我的DataFrame采用以下形式:

                  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

I can work with tuples, as index values, however I think it's better to work with a multilevel DataFrame. 我可以使用元组作为索引值,但我认为使用多级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 (ie from the initial creation), as the list within the dictionary as well as the tuples afterwards are adding a level of complication. 这样的帖子帮助我分两步创建它,但是我很难一步完成(即从最初的创建),因为字典中的列表以及之后的元组添加了一个级别并发症。

I think you are close, for MultiIndex is possible used MultiIndex.from_tuples method: 我认为你很接近,因为MultiIndex可能使用MultiIndex.from_tuples方法:

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

Thanks, Zero for another solution: 谢谢, Zero为另一个解决方案:

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

df.index = pd.MultiIndex.from_tuples(df.index)
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

I will using stack for two level dict .... 我将使用stack为两级dict ....

df=pd.DataFrame(d)

df.T.stack().apply(pd.Series)
Out[230]: 
               0  1  2  3  4    5    6
key1 sub-key1  a  b  c  d  e  NaN  NaN
key2 sub-key2  1  2  3  5  8    9   10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM