如何在 Pandas 中将日期四舍五入到周开始

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34539959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:26:51  来源:igfitidea点击:

How to round dates to week starts in Pandas

pythonpandas

提问by DanT

I'm having a DataFrame with a date column. How can I map each date dto the start day of the week containing d?

我有一个带有日期列的 DataFrame。如何将每个日期映射d到包含 的一周的开始日d

回答by DanT

import pandas as pd
df['Date'] - pd.to_timedelta(df['Date'].dt.dayofweek, unit='d')

回答by jedi

Here is an alternative approach for calculating beginning of the week series by using convenience method pd.DateOffset(weekday=0,weeks=1):

这是使用便捷方法计算周开始系列的另一种方法pd.DateOffset(weekday=0,weeks=1)

import pandas as pd, numpy as np
df=pd.DataFrame({'date':pd.date_range('2016-10-01','2016-10-31')})
df['BeginWeek']=np.where(df.date.dt.weekday==0, # offset on Non Mondays only
                         df['date'], 
                         df['date']-np.timedelta64(1,'W')), 
                         )

Thanks to ribitskyibnp.wherewas added to pick current Monday when date is already Monday. Confirmation that the above works now:

感谢ribitskyibnp.where被添加到当日期已经是星期一时选择当前星期一。确认以上工作现在:

enter image description here

在此处输入图片说明

Some additional ideas provided by others:

其他人提供的一些额外想法:

Here is a quick list of days of the week:

这是一周中的几天的快速列表:

df['BeginWeek'].dt.strftime("%a").unique() 
array(['Mon'], dtype=object)

and the days in the original column are:

原始列中的天数是:

df['date'].dt.strftime("%a").unique()
array(['Sat', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri'], dtype=object)