如何将Pandas透视表日期列按年月分组并排除当前月份?
Pandas透视表:保留当前月份日期列,其余按年月分组聚合
步骤1:确保日期列是datetime类型
如果你的order_date还不是datetime格式,先转换:
import pandas as pd df['order_date'] = pd.to_datetime(df['order_date'])
步骤2:生成原始透视表
执行你提供的代码生成透视表:
pivot = df.query('brand_name == "ishin"').pivot_table( index="channel_name", columns="order_date", values="qty", aggfunc="sum", fill_value=0, margins=False )
步骤3:拆分并处理列
定义「当前月份」
有两种常见定义方式,选其一即可:
- 方式1:使用系统当前时间的月份
current_month = pd.Timestamp.now().to_period('M') - 方式2:使用数据中最新日期的月份(如果业务中的「当前」指数据内最新月份)
current_month = pivot.columns.max().to_period('M')
分离当前月份列与其他列
# 筛选当前月份的日期列 current_month_cols = pivot.columns[pivot.columns.to_period('M') == current_month] # 筛选非当前月份的日期列 other_cols = pivot.columns[pivot.columns.to_period('M') != current_month]
对非当前月份列按年月分组求和
将非当前月份的列按「月份全称-年份」(如April-2023)分组,聚合求和:
# 分组求和,并重命名列格式 other_grouped = pivot[other_cols].groupby( lambda x: x.strftime('%B-%Y'), axis=1 ).sum() # 如果需要月份缩写(如Apr-2023),替换为 '%b-%Y'
合并结果
将当前月份的原始日期列和分组后的年月列合并:
result = pd.concat([pivot[current_month_cols], other_grouped], axis=1) # 可选:按时间顺序排序列 result = result.reindex(columns=sorted(result.columns, key=lambda x: pd.to_datetime(x) if '-' in x else x))
说明
to_period('M')将日期转换为年月周期,便于快速匹配当前月份- 分组时的
lambda函数负责将日期格式化为指定的年月字符串 - 合并后的结果既保留了当前月份的每日数据,又将历史月份的数据聚合为年月维度
内容的提问来源于stack exchange,提问作者Manas Ranjan
相关产品推荐
相关产品推荐

