我有两个看起来像这样的datframe
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
我想用posting_periods匹配的df1中的client1的销售额和df2中的client1的销售额之和来更新client1的df1中的销售额.换一种说法
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
标签:pandas,dataframe,python
来源: https://codeday.me/bug/20191108/2009784.html
该博客讨论如何使用Python的pandas库合并具有部分相同列的两个DataFrame,并将特定行的销售额相加。示例中,df1和df2分别包含'posting_period'、'name'和'sales'或'profit'列。博主展示了如何通过创建一个映射系列并使用索引列更新df1的'sales'列,以实现df1和df2中匹配行的销售额总和。

被折叠的 条评论
为什么被折叠?



