Katsu
Katsu

Reputation: 8875

Pandas Dataframe: Based a column of dates, create new column with last day of the month?

Haven't found anything addressing this in a pandas dataframe.

So far I've tried this based on another stack overflow post but it is not working:

df['last_day_in_month'] = pd.Period(pd.to_datetime(df['date']),freq='M').end_time.date()

Pls excuse the quick picture but basically trying to replicate this in a pandas dataframe: enter image description here

Upvotes: 0

Views: 612

Answers (2)

rhug123
rhug123

Reputation: 8768

Try this:

df['last_day_in_month'] = df['Date'] + pd.tseries.offsets.MonthEnd(0)

Upvotes: 1

lemon
lemon

Reputation: 15482

You can use pandas.Period with the corresponding month frequency to get the month, then catch the last day with the "end_time" attribute:

df['date'].apply(lambda d: pd.Period(d, freq='M').end_time.date()) 

Then you can assign this value to your new column.

Upvotes: 0

Related Questions