我试着解决这个问题 . 我有三个数据帧,我想根据第三个数据框中的值合并(连接?)其中两个数据帧 . 以下是数据帧:
DF1:
index,fields,a1,a2,a3,a4,a5
2018-06-01,price,1.1,2.1,3.1,4.1,5.1
2018-06-01,amount,15,25,35,45,55
2018-06-02,price,1.2,2.2,3.2,4.2,5.2
2018-06-02,amount,16,26,36,46,56
2018-06-03,price,1.3,2.3,3.3,4.3,5.3
2018-06-03,amount,17,27,37,47,57
DF2:
index,fields,b1,b2,b3
2018-06-01,clients,1,2,3
2018-06-02,clients,1,2,3
2018-06-03,clients,1,2,3
df1和df2中的列不同,但它们的关系是df3 .
DF3:
index,product1,product2
0,a1,b1
1,a2,b1
2,a3,b2
3,a4,b2
4,a5,b3
我想合并df1和df2中的数据,但保留与d1中相同的列(因为b1,b2,b3用a1,a2,a3,a4和a5引用) . 这是df4,我想要的理想数据帧 .
DF4:
index,fields,a1,a2,a3,a4,a5
2018-06-01,price,1.1,2.1,3.1,4.1,5.1
2018-06-01,amount,15,25,35,45,55
2018-06-01,clients,1,1,2,2,3
2018-06-02,price,1.2,2.2,3.2,4.2,5.2
2018-06-02,amount,16,26,36,46,56
2018-06-02,clients,4,4,5,5,6
2018-06-03,price,1.3,2.3,3.3,4.3,5.3
2018-06-03,amount,17,27,37,47,57
2018-06-03,clients,7,7,8,8,9
提前谢谢了,
2 回答
Unpivot
df2
使用df.melt:从参考表
df3
删除冗余列index
,使用melted df2
删除pd.merge:从合并结果中做pd.pivot_table:
使用pd.concat向
df1
添加新行,对行进行排序并重置索引:Result :
如果你重命名df2的列:
然后你可以做一个简单的concat:
你得到了所需的df4
但是在df2中,只有a1-a3,而在df4中有列a1-a5,所以df2的行将为a4,a5设置NaN,除非你以某种方式创建它们的列 . 你可以这样做:
......等