Anakin Skywalker
Anakin Skywalker

Reputation: 2520

Converting period[Q-DEC] column into a dataframe to a string in Python

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!

Upvotes: 2

Views: 4127

Answers (2)

BENY
BENY

Reputation: 323276

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

Upvotes: 1

wwnde
wwnde

Reputation: 26676

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

Upvotes: 3

Related Questions