Change year in pandas.DataFrame

Viewed 258

I have a large amount of time-series data where I want to change all the years within a certain range to year 1900 (for example). My MWE is

import pandas as pd
from datetime import date

df = pd.DataFrame({
    'name': ['alice','bob','charlie'],
    'date_of_birth': ['10/25/2005','10/29/2002','01/01/2001']})

# convert to type datetime
df['date_of_birth'] = pd.to_datetime(df['date_of_birth'])
print(df)

df['date_of_birth'] = df['date_of_birth'].mask(df['date_of_birth'].dt.year > 2000, \
                         df['date_of_birth'] - pd.to_timedelta(100, unit='y') + \
                         pd.to_timedelta(12, unit='h'))
print(df)

This method changes the year, as well as months and days. Is there a way to only change the year and leave everything else as is?

1 Answers

We can use date.replace:

s = df["date_of_birth"].apply(lambda x: x.replace(year=1900))
df["date_of_birth"] = np.where(df["date_of_birth"].dt.year > 2000, s, df["date_of_birth"])
      name date_of_birth
0    alice    1900-10-25
1      bob    1900-10-29
2  charlie    1900-01-01
Related