Subtract two Pandas DataFrames joined on multiple column values

前端 未结 2 1045
长发绾君心
长发绾君心 2021-01-22 15:45

I am trying to subtract the values of a column in DataFrame A, from the values from a column in DataFrame B, but only if multiple column values are equal to each other.

2条回答
  •  不要未来只要你来
    2021-01-22 15:51

    This is why the Index is so useful, subtraction will be aligned on the indices (both rows and columns).

    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
    

提交回复
热议问题