求助:基于DataFrame日期列的年月生成assessmentYear(AY)列
解决方案
要实现基于日期生成连续编号的评估年(AY)列,你可以通过日期分组+连续编号映射的方式完成,全程基于date列而非索引,适合处理25000+行的大数据量。
步骤1:确保日期列是datetime类型
首先将字符串格式的date列转换为pandas的datetime类型,方便后续提取年月信息:
import pandas as pd import numpy as np # 构造样本DataFrame(实际使用时替换为你的数据) data = { 1: '2019-09-19', 2: '2019-09-20', 3: '2019-10-29', 4: '2019-10-30', 5: '2020-04-01', 6: '2020-04-02', 7: '2020-04-03', 8: '2020-04-04', 9: '2020-11-05', 10: '2020-11-06', 11: '2020-11-07', 12: '2020-11-08', 13: '2020-11-09', 14: '2021-04-10', 15: '2021-04-11', 16: '2021-04-12', } df = pd.DataFrame.from_dict(data, orient='index', columns=['date']) # 转换为datetime类型 df['date'] = pd.to_datetime(df['date'])
步骤2:生成评估周期的分组键
根据你的规则(评估年从当年10月到次年5月),为每个日期分配对应的周期标识:
- 10月及以后的日期,属于当前年份起始的评估周期(如2019-10 → 2019-2020)
- 5月及以前的日期,属于前一年起始的评估周期(如2020-04 → 2019-2020)
- 6-9月的日期(样本中未出现),默认归为前一年起始的周期(可根据业务需求调整)
用矢量化操作实现(比apply效率更高):
# 提取年月 df['year'] = df['date'].dt.year df['month'] = df['date'].dt.month # 确定周期的起始年份 df['start_year'] = np.where( df['month'] >= 10, df['year'], np.where(df['month'] <= 5, df['year'] - 1, df['year'] - 1) ) # 生成周期标识(如"2019-2020") df['period'] = df['start_year'].astype(str) + '-' + (df['start_year'] + 1).astype(str)
步骤3:映射为连续的AY编号
将唯一的周期按时间顺序排序,然后分配从1开始的连续编号,最终生成assessmentYear(AY)列:
# 按时间顺序获取唯一周期 unique_periods = sorted(df['period'].unique()) # 创建周期到AY编号的映射 period_to_ay = {period: f"AY{i+1}" for i, period in enumerate(unique_periods)} # 生成最终的AY列 df['assessmentYear(AY)'] = df['period'].map(period_to_ay) # 清理中间辅助列(可选) df.drop(['year', 'month', 'start_year', 'period'], axis=1, inplace=True)
最终结果
运行后你的样本数据会得到如下结果:
| date | assessmentYear(AY) |
|---|---|
| 2019-09-19 | AY1 |
| 2019-09-20 | AY1 |
| 2019-10-29 | AY2 |
| 2019-10-30 | AY2 |
| ... | ... |
| 2020-11-05 | AY3 |
| ... | ... |
这种方法完全基于date列的逻辑,不受索引影响,且矢量化操作能高效处理25000+行的数据。
内容的提问来源于stack exchange,提问作者srinivas
相关产品推荐
相关产品推荐

