Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to offset Date to the beginning of the month?

Tags:

python

pandas

I have the data frame that goes more or less like this:

Date    x   y   z
1998-01-30  000445  Abbey National Plc  2.24455118179321
1998-01-30  001097  Mytravel Group  1.55792689323425

The 'Date' column is datetime64[ns] type and I would like to offset the 'Date' column so that my date would shift to the beginning of the month, so this should go like this:

df['New Date'] = df['Date'].offsets.MonthBegin()

But returns an error:

AttributeError: 'Series' object has no attribute 'offsets'

Why so? a single df column is series, right?

type(df['Date'])
Out[83]: pandas.core.series.Series
like image 959
krakowi Avatar asked Nov 21 '25 06:11

krakowi


1 Answers

You could try

df['New_date'] = df.set_index('Date').index.to_period('M').to_timestamp('D')

This assumes that Date is already a datetime object. If it isn't, then first convert using.

df['Date'] = pd.to_datetime(df['Date'])

It's not essential, but good practice to add an underscore in between column names. So New_date instead of New date. Possibly make this lowercase also.

like image 70
Josmoor98 Avatar answered Nov 22 '25 19:11

Josmoor98



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!