处理pandas的resample函数按周取样后日期都是星期日
1、问题描述:
用resample函数后,索引都是周日,一周的最后一天,并非实际的工作日。
2、解决方法
增加一列对比列,保存实际工作日期:
df[‘compdate’].resample(‘W’).max()
df.index = pd.to_datetime(df.index)
df['compdate'] = df.index
print(df)
# 实际最后交易日,非周末 ,索引都是周末最后一天,星期日。
#print(df['compdate'].resample('W').max())
df_week = pd.DataFrame({'open':df['open'].resample('W').first(),
'close':df['close'].resample('W').last(),
'high':df['high'].resample('W').max(),
'low':df['low'].resample('W').min(),
'volume':df['volume'].resample('W').sum(),
'lastdate':df['compdate'].resample('W').max() })
print(df_week)
结果效果如下:
索引date列红色框内,都是周日的日期,lastdate是实际工作的交易日期。
如蓝色框所示:
2023-5-21是周日,2023-5-19是周五,实际工作日。