我有两个像这样的数据框
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/