I have a dataset where I would like to convert the values within a specific column to a long date. The long date will always be the first of the first month of that quarter.
**Ex. Q122 = 1/1/2022, Q222 = 4/1/2022, Q322 = 7/1/2022, Q422 = 10/1/2022**
Data
ID Date Location
AA Q123 NY
BB Q425 CA
CC Q226 NY
CC Q326 NY
Desired
ID Date Location LongDate
AA Q123 NY 1/1/2023
BB Q425 CA 10/1/2025
CC Q226 NY 4/1/2026
CC Q326 NY 7/1/2026
Doing
df['Date'] = pd.PeriodIndex(qs, freq='Q').to_timestamp()
Error is unable to parse. I am thinking there has to be initial conversion here. Researching this, any suggestion is appreciated.
CodePudding user response:
You can do with reversing the pattern:
pd.to_datetime(df['Date'].str[-2:] df['Date'].str[:2]).dt.strftime('%m/%d/%Y')
0 01/01/2023
1 10/01/2025
2 04/01/2026
3 07/01/2026
Name: Date, dtype: object
Note that .dt.strftime('%m/%d/%Y')
should be only used if you want them as strings. I recommend you dont use them and let it be date