Pandas return the next Sunday for every row

人盡茶涼 提交于 2020-08-27 21:27:01

问题


In Pandas for Python, I have a data set that has a column of datetimes in it. I need to create a new column that has the date of the following Sunday for each row.

I've tried various methods trying to use iterrows and then figure out the day of the week, and add a day until the day is 7, but it hasn't worked and I'm not even sure how I'd return the date instead of just the day number then. I also don't feel like iterrows would be the best way to do it either.

What is the best way to return a column of the following Sunday from a date column?


回答1:


Use the Pandas date offsets, e.g.:

>>> pd.to_datetime('2019-04-09') + pd.offsets.Week(weekday=6)
Timestamp('2019-04-14 00:00:00')

For example, this changes the provided datetime over a week. This is vectorised, so you can run it against a series like so:

temp['sunday_dates'] = temp['our_dates'] + pd.offsets.Week(weekday=6)
    our_dates  random_data sunday_dates
0  2010-12-31         4012   2011-01-02
1  2007-12-31         3862   2008-01-06
2  2006-12-31         3831   2007-01-07
3  2011-12-31         3811   2012-01-01

N.b. The Week(weekday=INT) parameter is 0 indexed on Monday and takes values from 0 to 6 (inclusive). Thus, passing 0 yields all Mondays, 1 yields all Tuesdays, etc. Using this, you can make everything any day of the week you would like.

N.b. If you want to go to the last Sunday, just swap + to - to go back.

N.b. (Such note, much bene) The specific documentation on time series functionality can be found here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html




回答2:


The function

import datetime
def datetime_to_next_sunday(original_datetime):
    return original_datetime + datetime.timedelta(days=6-original_datetime.weekday())

returns the datetime.datetime shifted to the next sunday. Having

import pandas as pd
df = pd.DataFrame({'A': ['Foo', 'Bar'],
                   'datetime': [datetime.datetime.now(),
                                datetime.datetime.now() + datetime.timedelta(days=1)]})

the following line should to the job:

df['dt_following_sunday'] = df[['datetime']].applymap(datetime_to_next_sunday)



回答3:


I suggest to use calendar library

 import calendar
 import datetime as dt

 #today date 
 now = datetime.datetime.now()
 print (now.year, now.month, now.day, now.hour, now.minute, now.second)

 # diffrence in days between current date  and  Sunday
 difday =  7 - calendar.weekday(now.year, now.month, now.day)

 # Afterwards next Sunday from today
 nextsunday  = datetime.date(now.year, now.month , now.day + difday)

 print(nextsunday)

Write this function and use




回答4:


The accepted answer is the way to go, but you can also use Series.apply() and pandas.Timedelta() for this, i.e.:

df["ns"] = df["d"].apply(lambda d: d + pd.Timedelta(days=(6 if d.weekday() == 6 else 6-d.weekday())))

    d                             ns
0   2019-04-09 21:22:10.886702    2019-04-14 21:22:10.886702

Demo



来源:https://stackoverflow.com/questions/55600401/pandas-return-the-next-sunday-for-every-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!