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

Python:如何按年月作为索引实现数据透视并获取目标输出

年月分组计数透视表实现方案

你之前的代码只提取了月份维度统计,没有区分年份,导致2021和2022年的同月份数据被合并,自然不符合预期。以下是两种直接生成「年份为行、月份为列」计数透视表的方法:

步骤1:确保日期列是datetime类型

先把日期列转换为标准datetime格式(如果还未处理):

All_Insurer_Portal_Reindex['New_Booking/Issued Date'] = pd.to_datetime(All_Insurer_Portal_Reindex['New_Booking/Issued Date'])

步骤2:提取年份和月份字段

从日期列拆分出年、月作为单独字段,方便后续分组:

All_Insurer_Portal_Reindex['year'] = All_Insurer_Portal_Reindex['New_Booking/Issued Date'].dt.year
All_Insurer_Portal_Reindex['month'] = All_Insurer_Portal_Reindex['New_Booking/Issued Date'].dt.month

方法1:使用pivot_table生成透视表

通过透视表指定行、列维度和聚合规则:

pivot_table = pd.pivot_table(
    data=All_Insurer_Portal_Reindex,
    index='year',  # 行:年份
    columns='month',  # 列:月份
    values='New_Booking/Issued Date',  # 用于计数的字段(任意非空列均可)
    aggfunc='count',  # 聚合方式:计数
    fill_value=0  # 无数据的年月填充0
)

方法2:使用crosstab(更简洁)

交叉表天生适配这种行列计数场景:

cross_table = pd.crosstab(
    index=All_Insurer_Portal_Reindex['year'],
    columns=All_Insurer_Portal_Reindex['month'],
    dropna=False,
    margins=False  # 不需要总计行/列则设为False
).fillna(0)

可选优化:美化月份列名

如果想把数字月份改成更易读的格式(比如「9月」):

cross_table.columns = [f'{month}月' for month in cross_table.columns]

生成的结果会以2021、2022为行索引,9、10月为列名,单元格对应各年月的记录计数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:05:25