减去在多个列值上联接的两个Pandas数据帧

2024-10-03 23:24:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从数据帧B中的列中减去数据帧a中某列的值,但前提是多个列值彼此相等。在

假设(虚构):

DataFrame A:
Index    Department  Speciality   TargetMonth Capacity
1        Sales       Cars         2019-1      150
2        Sales       Cars         2019-2      120
3        Sales       Furniture    2019-1      110
4        IT          Servers      2019-1      100

DataFrame B:
Index    Department  Speciality   TargetMonth Required
1        Sales       Cars         2019-1      100
2        Sales       Cars         2019-2      120
3        IT          Servers      2019-1      50
4        Sales       Furniture    2019-1      50

我故意交换了数据帧B中索引3和4的顺序,而不是A。我的目标是从数据框A的capacity列中减去DataFrame B的Required列作为所需容量小时数,从而得到另一个不一定需要排序的列表:

^{pr2}$

因此,从技术上讲,只有当所有列值都匹配并且不基于顺序时,才进行减法,因为在一个或另一个列表中可能缺少某些行。在

我可以用一些for循环和条件来解决这个问题,但是我想有一个干净整洁的Pandas方法来解决这个问题,尽管它是我目前所坚持的“连接”部分。在

感谢您提前抽出时间。在


Tags: 数据dataframe列表index顺序requireditcars
2条回答

这就是Index如此有用的原因,减法将在索引(行和列)上对齐。在

dfA = dfA.set_index(['Department', 'Speciality', 'TargetMonth'])
dfB = dfB.set_index(['Department', 'Speciality', 'TargetMonth'])

dfA.sub(dfB.rename(columns={'Required': 'Capacity'}), fill_value=0)

                                   Capacity
Department Speciality TargetMonth          
IT         Servers    2019-1             50
Sales      Cars       2019-1             50
                      2019-2              0
           Furniture  2019-1             60

我会使用合并键:

对于此解决方案,将数据帧A作为dfA,将数据帧作为dfB

   df_result =  pd.merge(dfA, dfB, how='inner', on=['Department','Speciality','TargetMonth'])

这将基于键['Department'、'Speciality'、'TargetMonth']将数据帧组合在一起,并将生成一个数据帧,其中键出现在两个数据帧中(how='inner')。在

即,如果dfB中有一个密钥是:

^{pr2}$

此值不会出现在数据帧df_result中。更多信息可以在这里找到-https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html

然后使用Pandas矢量化的解决方案:

   df_result['Result'] = df_result['Capacity'] - df_result['Required']

相关问题 更多 >