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

Pandas按userID及活动是否为running条件分组求和问题

解决方案
  • 新增标记列
    用两种方式都可以生成标记是否为running的列:
    import numpy as np
    # 方法1:np.where判断赋值
    df['is_running'] = np.where(df['activity'] == 'running', 1, 0)
    
    # 方法2:布尔值转整数(更简洁)
    df['is_running'] = (df['activity'] == 'running').astype(int)
    
  • 分组求和
    基于userID和新增的is_running列分组,对count列求和:
    # 得到多级索引结果
    result = df.groupby(by=["userID", "is_running"])["count"].sum()
    
    # 如果需要展开为普通表格(消除多级索引),加上reset_index
    result = df.groupby(by=["userID", "is_running"])["count"].sum().reset_index()
    

针对你的示例数据,最终结果会是:

userIDis_runningcount
303
3111

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:55:58