pandas 数据帧从嵌套字典 [英] Pandas dataframe from nested dictionary
问题描述
我的字典如下所示:
{'x': {'b': 10, 'c': 20}, 'y': {'b': '33', 'c': 44}}
我想得到一个如下所示的数据框:
I want to get a dataframe that looks like this:
index col1 col2 val
0 x b 10
1 x c 20
2 y b 33
3 y c 44
pandas.from_dict(),但它没有给我所需的结果。
那么,最优雅,实用的方法是什么?
I tried calling pandas.from_dict(), but it did not give me the desired result. So, what is the most elegant, practical way to achieve this?
编辑:在现实中,我的字典是深度4,所以我想查看一个解决方案,或者理想情况下,这个解决方案适用于一般设置中的任意深度。
In reality, my dictionary is of depth 4, so I'd like to see a solution for that case, or ideally, one that would work for arbitrary depth in a general setup.
这是一个更深入的字典的例子:
':'''''',''''',''',''','' 'y':{'a':{'m':100,'n':200},'b':{'m':111,'n':222}}} 适当的数据框应该有8行。
Here is an example of a deeper dictionary:
{'x':{'a':{'m':1, 'n':2}, 'b':{'m':10, 'n':20}}, 'y':{'a':{'m':100, 'n':200}, 'b':{'m':111, 'n':222}} }
The appropriate dataframe should have 8 rows.
答案:
df = pd.DataFrame([(k1, k2, k3, k4, k5, v) for k1, k2345v in dict.items()
for k2, k345v in k2345v.items()
for k3, k45v in k345v.items()
for k4, k5v in k45v.items()
for k5, v in k5v.items()])
推荐答案
您可以使用列表com将你的dict重新排列成每个元组一行的元组列表,然后你可以对数据框进行排序。
You can use a list comprehension to reorder your dict into a list of tuples where each tuple is a row and then you can sort your dataframe
import pandas as pd
d = {'x': {'b': 10, 'c': 20}, 'y': {'b': '33', 'c': 44}}
df = pd.DataFrame([(k,k1,v1) for k,v in d.items() for k1,v1 in v.items()], columns = ['Col1','Col2','Val'])
print df.sort(['Col1','Col2','Val'], ascending=[1,1,1])
Col1 Col2 Val
3 x b 10
2 x c 20
1 y b 33
0 y c 44
这篇关于 pandas 数据帧从嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!