You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中通过计算字段调整Q4 28列,使Q1-Q4和等于rounded_sum?

需求与解决方案建议

需求说明

计算DataFrame中rounded_sum与rounded_sum_2的差值delta,将该delta应用于Q4 28列(加或减),确保Q1 28至Q4 28列的总和等于rounded_sum列。

原始数据

Location    range   type    Q1 28   Q2 28   Q3 28   Q4 28   rounded_sum rounded_sum_2
NY          low_r   AA      2       0       0       0       2           2
NY          low_r   AA      2       2       2       6       8           12
NY          low_g   BB      0       0       0       0       0           0
NY          low_g   BB      0       0       2       4       4           6
CA          low_r   AA      0       2       4       4       6           10
CA          low_r   AA      2       2       4       8       12          16
CA          low_g   BB      0       0       0       0       0           0
CA          low_g   BB      0       0       0       2       2           2

期望结果

Location   range   type    Q1 28   Q2 28   Q3 28   Q4 28   rounded_sum rounded_sum_2
    NY      low_r   AA      2       0       0       0       2           2
    NY      low_r   AA      2       2       2       2       8           12
    NY      low_g   BB      0       0       0       0       0           0
    NY      low_g   BB      0       0       2       2       4           6
    CA      low_r   AA      0       2       4       0       6           10
    CA      low_r   AA      2       2       4       4       12          16
    CA      low_g   BB      0       0       0       0       0           0
    CA      low_g   BB      0       0       0       2       2           2

当前尝试的代码

delta = df['rounded_sum'].sub(df['rounded_sum_2'])
#add or subtract delta to [Q4 28']
df['Q4 28'] = df['Q4 28'].add(delta)

解决方案建议

当前思路方向正确,但需要调整delta的计算逻辑:核心需求是让Q1-Q4的总和匹配rounded_sum,所以正确的delta应该是目标总和与当前Q1-Q4总和的差值,而非rounded_sum和rounded_sum_2的直接相减。

基础实现代码

# 计算当前Q1到Q4的总和
current_sum = df[['Q1 28', 'Q2 28', 'Q3 28', 'Q4 28']].sum(axis=1)
# 计算需要调整的差值:目标总和 - 当前总和
delta = df['rounded_sum'] - current_sum
# 将差值应用到Q4 28列
df['Q4 28'] += delta

计算字段式实现(Pandas assign方法)

如果想用无中间变量的计算字段方式,可直接生成最终结果:

df = df.assign(
    current_sum=lambda x: x[['Q1 28', 'Q2 28', 'Q3 28', 'Q4 28']].sum(axis=1),
    delta=lambda x: x['rounded_sum'] - x['current_sum'],
    **{'Q4 28': lambda x: x['Q4 28'] + x['delta']}
).drop(columns=['current_sum', 'delta'])

内容的提问来源于stack exchange,提问作者Lynn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 08:47:32