如何用Pandas从时序DataFrame提取月末倒数第2、3、4工作日特征列?
实现时序DataFrame提取月末倒数工作日标记列的方案
需求说明
现有一个时序DataFrame,包含Date、temp_data、holiday、day列,数据示例如下:
Date temp_data holiday day 01.01.2000 10000 0 1 02.01.2000 0 1 2 03.01.2000 2000 0 3 .. 26.01.2000 200 0 26 27.01.2000 0 1 27 28.01.2000 500 0 28 29.01.2000 0 1 29 30.01.2000 200 0 30 31.01.2000 0 1 31 01.02.2000 0 1 1 02.02.2000 2500 0 2
其中holiday=0为工作日(有数据),holiday=1为非工作日(无数据)。需要生成三个新列:
secondlast_wd:标记当月倒数第2个工作日thirdlast_wd:标记当月倒数第3个工作日fourthlast_wd:标记当月倒数第4个工作日
最终输出DataFrame示例如下:
Date temp_data holiday day secondlast_wd thirdlast_wd fourthlast_wd 01.01.2000 10000 0 1 1 0 0 02.01.2000 0 1 2 0 0 0 03.01.2000 2000 0 3 0 0 0 .. 25.01.2000 345 0 25 0 0 1 26.01.2000 200 0 26 0 1 0 27.01.2000 0 1 27 0 0 0 28.01.2000 500 0 28 1 0 0 29.01.2000 0 1 29 0 0 0 30.01.2000 200 0 30 0 0 0 31.01.2000 0 1 31 0 0 0 01.02.2000 0 1 1 0 0 0 02.02.2000 2500 0 2 0 0 0
实现方案(Python Pandas)
步骤1:预处理日期列
先将Date列转换为datetime类型,方便按月份分组:
import pandas as pd # 假设原始数据存储在df中 df['Date'] = pd.to_datetime(df['Date'], format='%d.%m.%Y')
步骤2:按月份分组提取目标工作日
对每个月份的分组,筛选出工作日(holiday=0),按日期排序后提取倒数第2、3、4个日期:
# 按年份+月份分组,仅保留工作日数据 grouped = df[df['holiday'] == 0].groupby([df['Date'].dt.year, df['Date'].dt.month]) # 存储每个月的目标工作日日期 target_dates = { 'secondlast_wd': [], 'thirdlast_wd': [], 'fourthlast_wd': [] } for (year, month), group in grouped: # 按日期升序排序,确保取的是月末方向的倒数工作日 sorted_workdays = group.sort_values('Date')['Date'].tolist() # 根据工作日数量提取对应倒数位置的日期 if len(sorted_workdays) >= 2: target_dates['secondlast_wd'].append(sorted_workdays[-2]) if len(sorted_workdays) >= 3: target_dates['thirdlast_wd'].append(sorted_workdays[-3]) if len(sorted_workdays) >= 4: target_dates['fourthlast_wd'].append(sorted_workdays[-4])
步骤3:生成标记列
初始化三个新列为0,再将对应目标日期标记为1:
# 初始化新列 df['secondlast_wd'] = 0 df['thirdlast_wd'] = 0 df['fourthlast_wd'] = 0 # 标记对应的日期 df.loc[df['Date'].isin(target_dates['secondlast_wd']), 'secondlast_wd'] = 1 df.loc[df['Date'].isin(target_dates['thirdlast_wd']), 'thirdlast_wd'] = 1 df.loc[df['Date'].isin(target_dates['fourthlast_wd']), 'fourthlast_wd'] = 1
步骤4:可选:恢复日期格式
如果需要将Date列转回原始的dd.mm.yyyy字符串格式:
df['Date'] = df['Date'].dt.strftime('%d.%m.%Y')
说明
- 自动处理每个月工作日数量不足的情况(比如某月份只有3个工作日,
fourthlast_wd不会产生任何标记) - 按年份+月份组合分组,避免不同年份同月份的数据混淆
- 排序逻辑确保提取的是月末方向的倒数工作日,而非月初方向
内容的提问来源于stack exchange,提问作者Bella_18
相关产品推荐
相关产品推荐

