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

如何在Pandas GroupBy处理后为数据行分配首行1、逐行减半的权重

实现Pandas分组后按规则添加权重列

需求:对DataFrame按Account列分组,为每组数据添加weights列,规则为每组首行权重设为1,后续每行权重为前一行的一半。

示例数据

import pandas as pd

df = pd.DataFrame({'Account': [1, 2, 3, 1, 2, 3, 3], 'Money': [4, 5, 6, 8, 9, 10, 11]})

高效实现方案(向量化操作)

利用groupby.cumcount()生成组内行索引,结合幂运算直接计算权重,这是性能最优的方案,适合大数据集:

# 为原DataFrame添加权重列
df['weights'] = 0.5 ** df.groupby('Account').cumcount()

# 查看结果
print(df)

输出结果:

Account  Money  weights
0        1      4     1.00
1        2      5     1.00
2        3      6     1.00
3        1      8     0.50
4        2      9     0.50
5        3     10     0.50
6        3     11     0.25

逻辑说明

  • df.groupby('Account').cumcount()会为每组内的行生成从0开始的连续整数(首行=0,第二行=1,第三行=2...)
  • 0.5 ** 索引值正好满足权重规则:首行0.5^0=1,第二行0.5^1=0.5,第三行0.5^2=0.25,以此类推

若需先过滤每组前N行再计算权重

如果需要先取每组前2行(如示例中的head(2)操作),可先过滤再添加权重:

# 过滤每组前2行
df_filtered = df.groupby('Account').head(2).reset_index(drop=True)
# 添加权重列
df_filtered['weights'] = 0.5 ** df_filtered.groupby('Account').cumcount()

# 查看结果
print(df_filtered)

输出结果:

Account  Money  weights
0        1      4     1.00
1        1      8     0.50
2        2      5     1.00
3        2      9     0.50
4        3      6     1.00
5        3     10     0.50

备选方案(apply逐组处理)

如果更倾向于逐组逻辑的直观写法,也可以用groupby.apply实现,但性能略低于向量化方案:

def add_weights(group):
    # 为每组生成权重序列:1, 0.5, 0.25...
    group['weights'] = [0.5 ** i for i in range(len(group))]
    return group

df = df.groupby('Account').apply(add_weights).reset_index(drop=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:37:48