Python从pandas date列获取一周的前一天(在我的示例中为星期四) [英] Python get previous day of week (Thursday in my example) from pandas date column

查看:387
本文介绍了Python从pandas date列获取一周的前一天(在我的示例中为星期四)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫日期"列,我想返回上一个星期四的日期(可以是一周中的任何一天).我使用pd.offsets.Week,但是当年份更改并且Week重新开始时,我没有得到预期的结果.这是我的数据框,其为"d":

I have a pandas date column and I want to return the date for the previous Thursday (could be any day of week). I use pd.offsets.Week but I do not get the expected result when the year changes and the Week starts over. Here is my dataframe as 'd':

raw date Thursday week_start 0 2019-01-03 2018-12-27 2018-12-27 1 2019-01-03 2018-12-27 2018-12-27 2 2019-01-03 2018-12-27 2018-12-27 3 2019-01-02 2018-12-27 2018-12-27 4 2019-01-02 2018-12-27 2018-12-27 5 2019-01-02 2018-12-27 2018-12-27 6 2019-01-03 2019-01-03 2018-12-27 7 2019-01-03 2019-01-03 2018-12-27 8 2019-01-03 2019-01-03 2018-12-27 9 2019-01-03 2019-01-03 2018-12-27 10 2019-01-02 2018-12-27 2018-12-27 11 2019-01-02 2018-12-27 2018-12-27 12 2019-01-02 2018-12-27 2018-12-27

raw date Thursday week_start 0 2019-01-03 2018-12-27 2018-12-27 1 2019-01-03 2018-12-27 2018-12-27 2 2019-01-03 2018-12-27 2018-12-27 3 2019-01-02 2018-12-27 2018-12-27 4 2019-01-02 2018-12-27 2018-12-27 5 2019-01-02 2018-12-27 2018-12-27 6 2019-01-03 2019-01-03 2018-12-27 7 2019-01-03 2019-01-03 2018-12-27 8 2019-01-03 2019-01-03 2018-12-27 9 2019-01-03 2019-01-03 2018-12-27 10 2019-01-02 2018-12-27 2018-12-27 11 2019-01-02 2018-12-27 2018-12-27 12 2019-01-02 2018-12-27 2018-12-27

d['week_start'] = d['raw date'] - pd.offsets.Week(weekday=3)

我希望d ['week_start'] = 1/3/2019返回1/3/2019,而不是12/27/2018.我怀疑这是因为在1/3/2019的Week为0,所以它返回了该周的星期四.无论年份如何变化,如何获取上一个星期四的日期?

I expected where d['week_start'] = 1/3/2019 to return 1/3/2019, not 12/27/2018. I suspect it is because the Week at 1/3/2019 is 0 so it returns the Thursday of that week. How can I get the previous Thursday's date regardless of a change in the year?

推荐答案

您可以使用 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆