如何在 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
How to round dates to week starts in Pandas
提问by DanT
I'm having a DataFrame with a date column. How can I map each date d
to 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.where
was added to pick current Monday when date is already Monday. Confirmation that the above works now:
感谢ribitskyibnp.where
被添加到当日期已经是星期一时选择当前星期一。确认以上工作现在:
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)