pythonpandas

How to offset Date to the beginning of the month?


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

Solution

  • 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.