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

如何实现groupby().sum()但不对同一wallet的重复token_transfers值求和

解决方案

要实现按position_type统计token_transfers总量,且同一钱包在同一类型下仅计算一次token_transfers,可以通过先去重再分组求和的方式解决:

步骤1:去除重复的(wallet, position_type)组合

由于同一钱包的token_transfers值唯一,且同一钱包同一position_type的多行数据里token_transfers完全相同,先保留每个(wallet, position_type)组合的唯一行:

unique_records = df.drop_duplicates(subset=['wallet', 'position_type'])

步骤2:按position_type分组求和

基于去重后的数据集,直接按position_type对token_transfers求和即可得到正确结果:

total_token_transfers_per_position_type = unique_records.groupby('position_type')['token_transfers'].sum()

合并为一行代码

也可以将两步合并,简化为:

total_token_transfers_per_position_type = df.drop_duplicates(subset=['wallet', 'position_type']).groupby('position_type')['token_transfers'].sum()

验证结果

执行后得到的结果为:

position_type
LD          455
Sushi_LP    455
Name: token_transfers, dtype: int64

完全符合预期的正确结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:50:24