python - 通过替换计算两个数据框中两列的减法

标签 python pandas subtraction

我有df1其中包含:

IDs    values
E21    32
DD12   82
K99    222

df2包含:

IDs   values
GU1   87
K99   93
E21   48

我需要的是检查 ID 是否在df2存在于 df1 , 减去 valuedf1 - df2为此ID并更新 valuedf2 .

如果IDdf2df1 中不存在,该值 IDdf2保持不变。

所以,上面例子的结果(基本上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/

相关文章:

python - 当 continue 命中时,是否有一种 Pythonic 方式在 'else' 循环中激活 'for'?

r - 如何获得矩阵中两列值之间的绝对差

java - Java中字符串的加法和减法

python - 如何在 python 中创建字典数组/列表?

python - Paramiko - 远程命令执行

python - 来自枢轴的 seaborn 热图中的数据顺序

python - 在 pyspark 中保留至少一个元素满足条件的组

python - 更改特定列中的值(pandas)

ios - 从 CGPath 中修剪/减去 CGPath?

python - Windows 7 上的 GetWindowRect 太小