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

如何用Pandas按月份统计布尔列的True值数量?

问题描述

我有一个DataFrame df,可通过以下代码生成:

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

请问如何按月份统计status_review和supply_review列中True值的数量?

期望输出如下:

month       # of true status_review      # of true supply_review  
2023-01-01           1                         1              
2022-12-01           1                         2
解决方案

在pandas中布尔值True会被视为1,False视为0,直接通过分组求和就能得到每个月的True值数量,以下是两种实现方式:

方法一:分组后直接求和

# 按month分组,对目标列求和
result = df.groupby('month')[['status_review', 'supply_review']].sum().reset_index()
# 重命名列名匹配期望输出
result.columns = ['month', '# of true status_review', '# of true supply_review']
print(result)

方法二:使用agg方法指定聚合规则

result = df.groupby('month').agg(
    **{
        '# of true status_review': ('status_review', 'sum'),
        '# of true supply_review': ('supply_review', 'sum')
    }
).reset_index()
print(result)

两种方法运行后都会输出符合预期的结果。

内容的提问来源于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:21:03