2

I am trying to convert period[Q-DEC] column into a string for modelling.

This answer helped me to do this.

My current data:

df = {'Month': [1, 8], 'Year': [2015, 2020]}
df = pd.DataFrame(data = df)
df['Quarter'] = (pd.to_datetime(df[['Month','Year']].astype(str)
               .agg('-'.join,1).radd("01-"),dayfirst=True).dt.to_period('Q'))

print(df)
df.dtypes

It gives me the output

   Month  Year Quarter
0      1  2015  2015Q1
1      8  2020  2020Q3
Month              int64
Year               int64
Quarter    period[Q-DEC]
dtype: object

Surprisingly I do not see many answer how to convert this period into string. I tried several solutions from this question. Appreciate any tips!

Anakin Skywalker
  • 2,400
  • 5
  • 35
  • 63

2 Answers2

3

Just .astype(str)

df.Quarter=df.Quarter.astype(str)
df.dtypes

Month       int64
Year        int64
Quarter    object
dtype: object

print(df)
 Month    Year Quarter
0      1  2015  2015Q1
1      8  2020  2020Q3
wwnde
  • 26,119
  • 6
  • 18
  • 32
1

You can try , also change the way you create the datetime

df['Quarter'] = pd.to_datetime(df.Year*10+df.Month,format='%Y%m').dt.to_period('q').astype(str)
Out[19]: 
0    2015Q1
1    2020Q3
dtype: object
BENY
  • 317,841
  • 20
  • 164
  • 234