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

如何在Pandas中按月份统计布尔列真值与case_id去重计数

按月份统计布尔值数量与case_id去重计数

数据构造

import pandas as pd
from io import StringIO
    
df = """  
    month       status_review             supply_review  case_id
2023-01-01           False                    False      12             
2023-01-01           True                     True       33           
2022-12-01           False                    True       45           
2022-12-01           True                     True       45         
2022-12-01           False                    False      44
    """
df= pd.read_csv(StringIO(df.strip()), sep='\s\s+', engine='python')

需求

按month分组完成以下统计:

  • 每个月status_review为True的记录数
  • 每个月supply_review为True的记录数
  • 每个月case_id的去重计数

期望输出格式:

month       # of true status_review      # of true supply_review  # of case
2023-01-01           1                         1                        2
2022-12-01           1                         2                        2

问题分析

直接使用groupby.sum()或groupby.agg('sum')会对case_id进行求和,而非去重计数,不符合需求:

df.groupby("month").sum()
df.groupby('month').agg('sum')

输出结果:

status_review    supply_review   case_id
month           
2022-12-01             1    2               134
2023-01-01             1    1               45

解决方案

使用groupby.agg()为每列指定单独的统计逻辑,精准控制各列的计算方式:

result = df.groupby('month').agg(
    **{
        '# of true status_review': ('status_review', 'sum'),
        '# of true supply_review': ('supply_review', 'sum'),
        '# of case': ('case_id', pd.Series.nunique)
    }
).reset_index()

print(result)

代码解释

  • ('status_review', 'sum'):布尔类型中True等价于1、False等价于0,求和即可得到True的总数量
  • ('case_id', pd.Series.nunique):调用nunique()方法统计去重后的case_id数量
  • reset_index():将month从分组索引转换为普通列,匹配期望的输出格式

运行后输出结果:

month  # of true status_review  # of true supply_review  # of case
0  2022-12-01                        1                        2          2
1  2023-01-01                        1                        1          2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:50:13