首页 > 解决方案 > Python 3.x:从两个不同形状的字典创建数据框

问题描述

与此处已发布的内容类似Create dataframe from two dictionaries。所有键都存在于两个字典中,唯一的区别是数组值的形状。

我有的:

d1 = {(1, "Autumn"): np.array([[2.5, 100], [4.5, 105], [7.5, 120], [9.5,137]]), (1, "Spring"): np.array([[10.5, 146], [11.7, 151], 
      [12.3, 164], [15.0, 173]])}
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, 100, 10.2], [4.5, 105, 13.3], [7.5, 120, 15.7], [9.5, 137, 18.8]], 
      columns = ["x", "y", "z"]), (1, "Spring"): pd.DataFrame([[10.5, 146, 15.6], [11.7, 151, 20], [12.3, 164, 23], [15.0, 173, 27]],
                columns = ["x", "y", "z"])}

你能帮帮我吗?我尝试使用作为答案发布的方法。但是,我得到ValueError: could not broadcast input array from shape (4,2) into shape (4)错误。

标签: pythonpython-3.xdictionary

解决方案


推荐阅读