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

如何基于datetime及其他列生成月度统计特征完成DataFrame转换

实现方法

基于Pandas可快速完成该转换需求,完整操作步骤及代码如下:


1. 基础字段预处理

先将原始日期列转换为标准日期格式,提取出后续分组需要的年月字段:

import pandas as pd

# 假设你的原始DataFrame变量名为df
# 转换日期格式,提取年月(格式为mm-YYYY,和你需求的列前缀一致)
df['date'] = pd.to_datetime(df['date'], format='%d-%m-%Y')
df['year_month'] = df['date'].dt.strftime('%m-%Y')

2. 分组聚合统计

按人员、年月两个维度分组,同时计算当月的记录数、吃水果总量两个指标:

grouped = df.groupby(['Person', 'year_month'], as_index=False).agg(
    size=('fruits eaten', 'count'),
    fruits=('fruits eaten', 'sum')
)

3. 转换为宽表结构

将分组后的长表转为你需要的宽表,同时拼接列名:

# 透视为宽表
pivot_result = grouped.pivot(
    index='Person', 
    columns='year_month', 
    values=['size', 'fruits']
)
# 拼接列名,调整为【年月_后缀】的格式
pivot_result.columns = [f'{col[1]}_{col[0]}' for col in pivot_result.columns]
# 缺失值填0,重置索引
pivot_result = pivot_result.reset_index().fillna(0).astype(int)

4. 可选:补全全年12个月的列

如果需要生成2015年全年12个月的所有特征列,新增以下代码即可,缺失月份的指标自动补0:

# 生成2015年全年12个月的所有目标列名
all_month_cols = []
for month in range(1, 13):
    month_str = f'{month:02d}-2015'
    all_month_cols.append(f'{month_str}_size')
    all_month_cols.append(f'{month_str}_fruits')

# 补全缺失列,按月份顺序调整列排序
for col in all_month_cols:
    if col not in pivot_result.columns:
        pivot_result[col] = 0
pivot_result = pivot_result[['Person'] + all_month_cols]

最终输出的pivot_result就是符合你要求的DataFrame。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 11:06:03