Python 3.x:从两个字典创建数据框 [英] Python 3.x: Create dataframe from two dictionaries

查看:143
本文介绍了Python 3.x:从两个字典创建数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python3.x。要实现的是:基于键合并字典并形成数据框。这将清除:

I'm working on Python 3.x. What is to be achieved is: merge dictionaries based on keys and form a dataframe. This would clear:

我拥有什么:

import numpy as np
import pandas as pd

d1 = {(1, "Autumn"): np.array([2.5, 4.5, 7.5, 9.5]), (1, "Spring"): np.array([10.5, 11.7, 12.3, 15.0])}
d2 = {(1, "Autumn"): np.array([10.2, 13.3, 15.7, 18.8]), (1, "Spring"): np.array([15.6, 20, 23, 27])}

我做什么想要实现:

d3 = {(1, "Autumn"): pd.DataFrame([[2.5, 10.2], [4.5, 13.3], [7.5, 15.7], [9.5, 18.8]], 
  columns = ["d1", "d2"]), (1, "Spring"): pd.DataFrame([[10.5, 15.6], [11.7, 20], 
            [12.3, 23], [15.0, 27]], columns = ["d1", "d2"])}

P。 S .:实际上,我正在研究 RandomForestRegressor 示例。上面的词典是训练和测试数据拆分后的X和y值。我想要实现的是在具有上述查询的图的数据框中并排获得X,y。字典的大小与两个字典中的键和每个键的值数目相同。

P. S.: I'm actually working on RandomForestRegressor example. The above dictionaries are my X and y values after the train and test data splits. What I'm trying to achieve is to get X, y side-by-side in a dataframe for plots with above query. The size of dictionary is same as are the key and number of values for each key in both dictionaries.

推荐答案

在两个字典中都存在(根据您的评论),您可以遍历一个字典的键,并为每个键从每个字典条目中创建一个数据框:

Since all keys are present in both dictionaries (according to your comment), you could iterate through the keys of one dictionary and make a dataframe from each dictionary entry for each key:

d3 = dict()
for k in d1.keys():
    d3[k] = pd.DataFrame(np.array([d1[k],d2[k]]).T, columns=["d1","d2"])

输出:

{(1, 'Autumn'):   
    d1    d2
 0  2.5  10.2
 1  4.5  13.3
 2  7.5  15.7
 3  9.5  18.8, 
(1, 'Spring'):    
    d1    d2
 0  10.5  15.6
 1  11.7  20.0
 2  12.3  23.0
 3  15.0  27.0}

这篇关于Python 3.x:从两个字典创建数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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