第一个解决方案是index
在df22
by Bankname
for align bydf1
中创建正确的行子运算:
df.set_index('BankName').sub(df2.set_index([['Bank1']]), fill_value=0)
df.set_index('BankName').sub(df2.set_index([['Bank2']]), fill_value=0)
您需要在df2
with中创建新列,在两个s 中都BankName
转换BankName
为,因此可以减去此行:index
DataFrame
df22 = df2.assign(BankName = 'Bank1').set_index('BankName')
df = df1.set_index('BankName').sub(df22, fill_value=0).reset_index()
print (df)
BankName Value1 Value2
0 Bank1 7.0 53.0
1 Bank2 15.0 65.0
2 Bank3 14.0 54.0
减去Bank2
:
df22 = df2.assign(BankName = 'Bank2').set_index('BankName')
df = df1.set_index('BankName').sub(df22, fill_value=0).reset_index()
print (df)
BankName Value1 Value2
0 Bank1 10.0 55.0
1 Bank2 12.0 63.0
2 Bank3 14.0 54.0
过滤器的另一种解决方案BankName
:
m = df1['BankName']=='Bank1'
df1.loc[m, df2.columns] = df1.loc[m, df2.columns].sub(df2.iloc[0])
print (df1)
BankName Value1 Value2
0 Bank1 7 53
1 Bank2 15 65
2 Bank3 14 54
m = df1['BankName']=='Bank2'
df1.loc[m, df2.columns] = df1.loc[m, df2.columns].sub(df2.iloc[0])