Tad
Tad

Reputation: 913

Python/Pandas - Rearrange string from column value

I would need to rearrange the column value on column: "Quarter" . Expected output should be as in column:"new_Quarter"

enter image description here

I got the column:"Quarter" from column:"Date" using the below code

df['Quarter'] = pd.PeriodIndex(df['Date'], freq='Q')

I tried to get the target column:"new_Quarter" using below code but getting an error

df['new_Quarter'] = q['Quarter'].str.slice(4,6) + ' ' + q['Quarter'].str.slice(2,4)

TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('

Upvotes: 3

Views: 583

Answers (1)

rafaelc
rafaelc

Reputation: 59274

You may use strftime

df['new_Quarter'] = df.Quarter.dt.strftime('Q%q %y')

As a side note, the column Quarter can also be simply created using to_period

df['Quarter'] = df.Date.dt.to_period('Q')

        Date Quarter new_Quarter
0 2019-09-18  2019Q3       Q3 19
1 2019-03-18  2019Q1       Q1 19
2 2019-05-13  2019Q2       Q2 19

Upvotes: 3

Related Questions