python - 使用等于相同 df 和另一个 df 的总和的值更新 pandas 数据框

标签 python pandas dataframe

我有两个像这样的数据框

df1

posting_period      name        sales       profit
    1               client1     50.00       10.00
    1               client2     100.00      20.00
    2               client1     150.00      30.00

df2 (this df does not have the 'profit' column as in df1) 

posting_period      name        sales       
    1               client1     10.00       
    2               client1     20.00   

我想用 client1 在 df1 中的销售额与 client1 在 df2 中的销售额之和更新 client1 在 df1 中的销售额,其中 posting_periods匹配。也就是说

desired result

posting_period      name        sales       profit
    1               client1     60.00       10.00
    1               client2     100.00      20.00
    2               client1     170.00      30.00

我正在使用的实际数据帧要大得多,但这些示例捕获了我正在努力完成的任务。我想出了一个非常迂回的方法,它不仅不起作用,而且不是很 pythonic。另一个挑战是 df1 中的附加列,而不是 df2 中的附加列。我希望有人可以提出替代方案。谢谢!

最佳答案

首先创建一个从df2映射索引列到sales的系列:

idx_cols = ['posting_period', 'name']
s = df2.set_index(idx_cols)['sales']

然后使用这个系列更新 df1['sales']:

df1['sales'] += pd.Series(df1.set_index(idx_cols).index.map(s.get)).fillna(0)

结果:

print(df1)

   posting_period     name  sales  profit
0               1  client1   60.0    10.0
1               1  client2  100.0    20.0
2               2  client1  170.0    30.0

关于python - 使用等于相同 df 和另一个 df 的总和的值更新 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51480105/

相关文章:

python - 打印指定范围内的列表Python

python - 延迟时间的问题

python - 试图绘制的 Pandas 类型错误

python - 如何将 Pandas 数据框列连接到可迭代列表中?

python - 在 Python 中调整日期时区的优雅方式

python - 重新排列行值

python - Pandas:如何通过以下方式连接数据帧?

python - 如何计算数据框中值可被 3 或 5 整除的行数?

python - 更快地评估数据帧的数学表达式

scala - 检查 arraytype 列是否包含 null