Pandas return the next Sunday for every row

2024/9/20 23:19:28

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?

Answer

Use the Pandas date offsets, e.g.:

>>> pd.to_datetime('2019-04-09') + pd.offsets.Week(n=0, 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(n=0, 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. Pass n=0 to keep a day, which is already on a Sunday, on that day. Pass n=1 if you want to force it to the next Sunday. 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

https://en.xdnf.cn/q/72289.html

Related Q&A

Where is `_softmax_cross_entropy_with_logits` defined in tensorflow?

I am trying to see how softmax_cross_entropy_with_logits_v2() is implemented. It calls _softmax_cross_entropy_with_logits(). But I dont see where the latter is defined. Does anybody know how to locate …

Python: Counting frequency of pairs of elements in a list of lists

Actually, I have a dataset about a "meeting". For example, A,B,C have a meeting, then the list would be [A,B,C]. Like this, each list would contain a list of members who participated in the …

How to create a pandas dataframe where columns are filled with random strings?

I want to create a Pandas dataframe with 2 columns and x number rows that contain random strings. I have found code to generate a pandas dataframe with random ints and a random stringer generator. I st…

Unable to make my script process locally created server response in the right way

Ive used a script to run selenium locally so that I can make use of the response (derived from selenium) within my spider.This is the web service where selenium runs locally:from flask import Flask, re…

using variable in a url in python

Sorry for this very basic question. I am new to Python and trying to write a script which can print the URL links. The IP addresses are stored in a file named list.txt. How should I use the variable in…

Create dynamic updated graph with Python

I need to write a script in Python that will take dynamically changed data, the source of data is not matter here, and display graph on the screen. I know how to use matplotlib, but the problem with m…

Converting a nested dictionary to a list

I know there are many dict to list questions on here but I cant quite find the information I need for my situation so Im asking a new quetion.Some background: Im using a hierarchical package for my mod…

Pandas dataframe : Operation per batch of rows

I have a pandas DataFrame df for which I want to compute some statistics per batch of rows. For example, lets say that I have a batch_size = 200000. For each batch of batch_size rows I would like to ha…

Combining grid/pack Tkinter

I know there have been many questions on grid and pack in the past but I just dont understand how to combine the two as Im having difficulties expanding my table in both directions (row/column).Buttons…

Mocking assert_called_with in Python

Im having some trouble understanding why the following code does not pass:test.pyimport mock import unittestfrom foo import Fooclass TestFoo(unittest.TestCase):@mock.patch(foo.Bar)def test_foo_add(self…