Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I adjust the dates of a column in pandas according to a threshhold?

I have a data frame with a datetime column like so:

  dates
0 2017-09-19
1 2017-08-28
2 2017-07-13

I want to know if there is a way to adjust the dates with this condition:

  1. If the day of the date is before 15, then change the date to the end of last month.
  2. If the day of the date is 15 or after, then change the date to the end of the current month.

My desired output would look something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  dates
0 2017-09-30
1 2017-08-31
2 2017-06-30

>Solution :

Using np.where and Josh’s suggestion of MonthEnd, this can be simplified a bit.

Given:

        dates
0  2017-09-19
1  2017-08-28
2  2017-07-13

Doing:

from pandas.tseries.offsets import MonthEnd

# Where the day is less than 15, 
    # Give the DateEnd of the previous month.
# Otherwise, 
    # Give the DateEnd of the current month.

df.dates = np.where(df.dates.dt.day.lt(15), 
                    df.dates.add(MonthEnd(-1)), 
                    df.dates.add(MonthEnd(0)))
print(df)

# Output:

       dates
0 2017-09-30
1 2017-08-31
2 2017-06-30
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading