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

在Jupyter Notebook中用Pandas基于Month列生成Quarters列

生成DataFrame季度列的几种实现方式

你的month列当前是object类型,可根据需求选择以下方法生成Quarters列:

方法1:字典映射(适配字符串/数值型month)

如果想保留month的字符串格式,直接用字符串键的映射字典:

# 兼容'01'/'1'这类不同格式的月份字符串
quarter_map = {'01':'Q1', '02':'Q1', '03':'Q1',
               '04':'Q2', '05':'Q2', '06':'Q2',
               '07':'Q3', '08':'Q3', '09':'Q3',
               '10':'Q4', '11':'Q4', '12':'Q4',
               '1':'Q1', '2':'Q1', '3':'Q1',
               '4':'Q2', '5':'Q2', '6':'Q2',
               '7':'Q3', '8':'Q3', '9':'Q3'}

df['Quarters'] = df['month'].map(quarter_map)

若将month转为整数型(更利于后续数据分析):

df['month'] = df['month'].astype(int)
quarter_map = {1:'Q1',2:'Q1',3:'Q1',4:'Q2',5:'Q2',6:'Q2',7:'Q3',8:'Q3',9:'Q3',10:'Q4',11:'Q4',12:'Q4'}
df['Quarters'] = df['month'].map(quarter_map)

方法2:分箱函数pd.cut()

适合已转为整数型的month列,自动划分区间生成季度:

df['month'] = df['month'].astype(int)
df['Quarters'] = pd.cut(df['month'],
                        bins=[0,3,6,9,12],
                        labels=['Q1','Q2','Q3','Q4'],
                        include_lowest=True)

方法3:数学计算生成

通过月份除以3向上取整,直接拼接季度标识:

import math

df['month'] = df['month'].astype(int)
df['Quarters'] = 'Q' + df['month'].apply(lambda x: str(math.ceil(x/3)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:54:33