[英]pandas datetime set Sunday as first day of the week
I've got a dataframe of pandas with a series of dates (all Sundays) like this: 我有一个带有一系列日期(所有星期日)的熊猫数据框,如下所示:
Date Year Week
2011-01-02 2011 52
2011-01-23 2011 3
2011-01-23 2011 3
2011-01-30 2011 4
2011-01-30 2011 4
The week is given by df['Date'].dt.week
, and what I want is set Sundays as the first day of the week, so I can get: 本周由
df['Date'].dt.week
,我想要的是星期日作为一周的第一天,所以我可以得到:
Date Year Week
2011-01-02 2011 1
2011-01-23 2011 4
2011-01-23 2011 4
2011-01-30 2011 5
2011-01-30 2011 5
How can I do that in the simplest way? 我怎么能以最简单的方式做到这一点?
PS I have failed to mention that there're multiple years in this dataset. PS我没有提到这个数据集中存在多年。 So for rare occasions there'll be the last day of the year is Sunday, I would like to get The 53rd week of this year other than The 1st week of next year .
因此,对于极少数情况,今年的最后一天是星期天,我想获得今年第53周,而不是明年的第一周 。
You can use dayofweek
to get that. 你可以使用
dayofweek
来获得它。
date = pd.DatetimeIndex(start='2011-01-02', end='2011-12-31',freq='D')
df = pd.DataFrame([date,date.year,date.week,date.dayofweek])
df = df.T
df.columns=['date','year','week','dayofweek']
df['newweek'] = 0
df.loc[df['dayofweek']==6, 'newweek'] = 1
df['newweek'] = df['newweek'].cumsum()
If you have multiple years, than do a rolling operation on the datetimeindex. 如果您有多年,则在datetimeindex上执行滚动操作。
A simple and quick answer would be the following: 一个简单快速的答案如下:
df['Week'] = df['Date'].apply(lambda x: (x + dt.timedelta(days=1)).week)
df
Date Year Week
0 2011-01-02 2011 1
1 2011-01-23 2011 4
2 2011-01-23 2011 4
3 2011-01-30 2011 5
4 2011-01-30 2011 5
Basically the first day is the Monday so applying a timedelta shifts your datetime (Sundays) to the following day (Mondays) 基本上第一天是星期一,因此应用timedelta会将您的日期时间(星期日)更改为次日(星期一)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.