我有df1
其中包含:
IDs values
E21 32
DD12 82
K99 222
和df2
包含:
IDs values
GU1 87
K99 93
E21 48
我需要的是检查 ID
是否在df2
存在于 df1
, 减去 value
的 df1
- df2
为此ID
并更新 value
在df2
.
如果ID
的 df2
在 df1
中不存在,该值 ID
在df2
保持不变。
所以,上面例子的结果(基本上df2
会被更新):
IDs values
GU1 87 #the same not changed since it not exist in df1
K99 129 #exist in df1, do the subtraction 222-93=129
E21 -16 #exist in df1, do the subtraction 32-48=129
有什么帮助吗?
最佳答案
# create new column in df2 with name 'new'
df2['new'] = df2['values']
# loop on the values of 'IDs' column
for i, element in enumerate(df2.IDs):
# condition to check if an element exists in df1
if element in df1.IDs.values:
df2['new'][i] = df1['values'][df1.index[df1.IDs == element][0]] - df2['values'][i]
# drop the old values column
df2.drop('values', axis = 1, inplace= True)
# rename the new values column
df2.rename(columns={'new': 'values'}, inplace= True)
关于python - 通过替换计算两个数据框中两列的减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60402776/