处理pandas的resample函数按周取样后日期都是星期日

处理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是周五,实际工作日。

猜你喜欢

转载自blog.csdn.net/qq_39065491/article/details/130871225