Byu*_*Lee 3 python subtraction dataframe pandas
df_1
product_name amount price
a 1 1
b 2 2
c 3 3
d 4 4
df_2
product_name amount
a 1
b 2
Run Code Online (Sandbox Code Playgroud)
这是熊猫中两个数据框的示例。
我希望把它减去amount
与product_names
类似a
产品将是amount
0,b
产品也达0 ...与product_name
列的值。
谢谢你的时间
选项 1
利用您的数据使用df.isin
:
mask = a.product_name.isin(b.product_name)
a.loc[mask, 'amount'] = 0
a
product_name amount price
0 a 0 1
1 b 0 2
2 c 3 3
3 d 4 4
Run Code Online (Sandbox Code Playgroud)
选项 2
set_index
+ reindex
+ subtract
。稍微更健壮,不设置为0
:
b = b.set_index('product_name').reindex(a.product_name).fillna(0)
a.amount -= b.amount.values
a
product_name amount price
0 a 0.0 1
1 b 0.0 2
2 c 3.0 3
3 d 4.0 4
Run Code Online (Sandbox Code Playgroud)