Reduce date values to reveal only 2 characters within the year (Pandas)

Viewed 49

I have a dataset where I would like to reduce a date column to reveal the YY vs YYYY

Data

ID      Date    Stat
AA11    Q1.2022 y
BB11    Q1.2022 y
BB11    Q1.2022 n

Desired

 ID     Date    Stat
 AA11   Q1.22   y
 BB11   Q1.22   y
 BB11   Q1.22   n

Doing

df['Date'] = df['Date'].astype(datetime).datetime[:-2]

Any suggestion is appreciated

2 Answers

Try this:

df['Date'] = df['Date'].astype(str).apply(lambda x: str(x[0:3])+str(x[-2:]))

Avoid using apply, better use a regex here:

df['Date'] = df['Date'].astype(str).str.replace(r'\.\d{2}', '.')

Or, if Date is already a string:

df['Date'] = df['Date'].str[:3]+df['Date'].str[-2:]
Related