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

如何用Pandas按月份统计success、fail、unknown的数量?

问题描述

给定可生成如下Pandas DataFrame的代码:

import pandas as pd
from io import StringIO

df = """  

               case_id    scheduled_date        status_code
               1213       2021-08               success
               3444       2021-06               fail
               4566       2021-07               unknown
               12213      2021-08               unknown
               34344      2021-06               fail
               44566      2021-07               unknown
               1213       2021-08               fail
              
        """
df= pd.read_csv(StringIO(df.strip()), sep='\s\s+', engine='python')

生成的DataFrame结构为:

case_id   scheduled_date  status_code
0   1213    2021-08         success
1   3444    2021-06         fail
2   4566    2021-07         unknown
3   12213   2021-08         unknown
4   34344   2021-06         fail
5   44566   2021-07         unknown
6   1213    2021-08         fail

需要按scheduled_date的月份,分别统计success、fail、unknown的数量,期望输出格式如下:

scheduled_date  num of success  num of fail  num of unknown

2021-08           1               1           1
2021-06           0               2           0
2021-07           0               0           2
解决方案

方法一:使用pd.crosstab(推荐)

crosstab可直接生成满足需求的交叉统计表,代码简洁高效:

# 生成交叉统计
result = pd.crosstab(
    index=df['scheduled_date'],
    columns=df['status_code'],
    colnames=[''],  # 移除列索引名称
    margins=False
).reset_index().rename_axis(None, axis=1)

# 重命名列名以匹配期望输出
result.columns = ['scheduled_date', 'num of success', 'num of fail', 'num of unknown']

print(result)

输出结果:

scheduled_date  num of success  num of fail  num of unknown
0        2021-06               0            2               0
1        2021-07               0            0               2
2        2021-08               1            1               1

方法二:使用pivot_table

如果需要更灵活的统计逻辑,可使用pivot_table:

result = df.pivot_table(
    index='scheduled_date',
    columns='status_code',
    values='case_id',  # 用任意非空列计数即可
    aggfunc='count',
    fill_value=0  # 填充缺失值为0
).reset_index().rename_axis(None, axis=1)

# 调整列名
result.columns = ['scheduled_date', 'num of success', 'num of fail', 'num of unknown']

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 21:45:12