问题描述
我有一个带有一系列日期(所有星期日)的熊猫数据框:
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
一周是由 df ['Date'].dt.week
给出的,而我想要的是将周日设置为一周的第一天,因此我可以得到:
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:
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?
P.S.我没有提到这个数据集中有很多年.因此,在极少数情况下,一年中的最后一天是星期日,除了明年1月的第一周,我想获得今年的第53周
P.S. I have failed to mention that there're multiple years in this dataset. 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.
推荐答案
您可以使用 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()
如果您有很多年,那么可以对datetimeindex进行滚动操作.
If you have multiple years, than do a rolling operation on the datetimeindex.
这篇关于 pandas 的日期时间将星期日设置为一周的第一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!