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

Time:06-15

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

CodePudding user response:

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.

CodePudding user response:

Try this:

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