在Pandas中按source和year计算剩余占比并补充数据行
问题:按source和year补充revenue_pct至100%的行
原始DataFrame如下:
import pandas as pd df = pd.DataFrame({'source': ['A', 'A', 'A', 'A', 'Z', 'Z'], 'target':['B', 'C', 'D', 'E', 'W', 'X'], 'revenue_pct':[0.1, 0.15, 0.12, 0.05, 0.4, 0.2], 'year':[2010, 2010, 2010, 2011, 2020, 2021]})
需求:按source和year分组,计算每组revenue_pct总和与1的差值,为每组添加一行target为unknown、revenue_pct为该差值的记录,最终得到如下预期结果:
预期结果DataFrame: df = pd.DataFrame({'source': ['A', 'A', 'A', 'A', 'A', 'A', 'Z', 'Z', 'Z', 'Z'], 'target':['B', 'C', 'D', 'unknown', 'E', 'unknown', 'W', 'unknown', 'X', 'unknown'], 'revenue_pct':[0.1, 0.15, 0.12, 0.63, 0.05, 0.95, 0.4, 0.6, 0.2, 0.8], 'year':[2010, 2010, 2010, 2010, 2011, 2011, 2020, 2020, 2021, 2021]})
解决方案
通过分组计算剩余百分比、构建补充数据、合并排序三步实现:
import pandas as pd # 原始数据 df = pd.DataFrame({'source': ['A', 'A', 'A', 'A', 'Z', 'Z'], 'target':['B', 'C', 'D', 'E', 'W', 'X'], 'revenue_pct':[0.1, 0.15, 0.12, 0.05, 0.4, 0.2], 'year':[2010, 2010, 2010, 2011, 2020, 2021]}) # 1. 分组计算每组剩余的revenue_pct(1减去组内总和) remainder_df = df.groupby(['source', 'year'])['revenue_pct'].sum().reset_index() remainder_df['revenue_pct'] = 1 - remainder_df['revenue_pct'] remainder_df['target'] = 'unknown' # 2. 合并原始数据和补充数据 final_df = pd.concat([df, remainder_df], ignore_index=True) # 3. 按source、year排序,并调整target顺序(让unknown排在同组最后) final_df = final_df.sort_values( by=['source', 'year', 'target'], ascending=[True, True, False] ).reset_index(drop=True) print(final_df)
执行后输出的final_df与预期结果完全一致,实现了按source和year补充剩余百分比的需求。
内容的提问来源于stack exchange,提问作者scrps93
相关产品推荐
相关产品推荐

