[英]Reading dataframe from dictionary of lists
I have a dictionary like below:我有一本像下面这样的字典:
d={0:[('cat_a', 15),('cat_b', 12)],
1: [('cat_a',10),('cat_b',7)],
2:[('cat_a', 12),('cat_b', 8)]}
I get a dataframe by using below:通过使用以下方法,我得到了 dataframe:
data = [l for l in d.values()]
df=pd.DataFrame(data,columns=['cat_a','cat_b'])
In each column i get tuples, out of which i only need the numerical value.在每一列中,我得到元组,其中我只需要数值。
Try:尝试:
df = pd.DataFrame(map(dict, d.values()))
print(df)
Prints:印刷:
cat_a cat_b
0 15 12
1 10 7
2 12 8
You can use:您可以使用:
df = pd.DataFrame.from_dict({k: {k2:v2 for k2,v2 in l} for k,l in d.items()}, orient='index')
# or for a functional approach like that of @Andrej
df = pd.DataFrame.from_dict(dict(zip(d, map(dict, d.values()))), orient='index')
output: output:
cat_a cat_b
0 15 12
1 7 10
2 12 8
used input:使用的输入:
d = {0: [('cat_a', 15),('cat_b', 12)],
1: [('cat_b',10),('cat_a',7)],
2: [('cat_a', 12),('cat_b', 8)]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.