Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas previous month begin

Given a dataframe:

df = pd.DataFrame({'c':[0,1,1,2,2,2],'date':pd.to_datetime(['2016-01-01','2016-02-01','2016-03-01','2016-04-01','2016-05-01','2016-06-05'])})

How to get the previous month begin for each date? The below doesn't work for 6/5 and there is some extra time portion.

pd.to_datetime(df['date'], format="%Y%m") + pd.Timedelta(-1,unit='M') + MonthBegin(0)

EDIT

I have a workaround (2 steps back and 1 step forward):

(df['date']+ pd.Timedelta(-2,unit='M')+ MonthBegin(1)).dt.date

Don't like this. There should be something better.

like image 231
iwbabn Avatar asked Jan 08 '17 02:01

iwbabn


People also ask

How do I get start and end date month data from a specific date in python?

You can use current_date. replace(day=1) to get first day in current month. And if you substract datetime. timedelta(days=1) then you get last day in previous month.

How do pandas get first date of the month?

The is_month_start attribute of Pandas. Timestamp, which is an equivalent of Python's date time-object, is used to check if a given date is the first day of the month or not.


1 Answers

You can first subtract MonthEnd to get to the end of the previous month, then MonthBegin to get to the beginning of the previous month:

df['date'] - pd.offsets.MonthEnd() - pd.offsets.MonthBegin()

The resulting output:

0   2015-12-01
1   2016-01-01
2   2016-02-01
3   2016-03-01
4   2016-04-01
5   2016-05-01
like image 63
root Avatar answered Jan 03 '23 12:01

root