How to get 'Q' at the beginning of every quarter

Viewed 57

I do have the below code which gives me the quarter from my date column and is working fine.

CODE

order['Qtr'] = pd.to_datetime(order['Order Date']).dt.quarter

OUTPUT

enter image description here

My requirement is i would like to add Q at the beginning of every quarter with the column name as Quarter . I want the output as below.

Required Output

enter image description here

Regards,

Bharath Vikas

2 Answers

First idea is convert values to strings and prepend Q:

order['Quarter'] = 'Q' + pd.to_datetime(order['Order Date']).dt.quarter.astype(str)

Or convert values to quarter periods and then use strftime:

rng = pd.date_range('2017-04-03', periods=10, freq='170D')
order = pd.DataFrame({'Order Date': rng})  

order['Quarter'] = pd.to_datetime(order['Order Date']).dt.to_period('q').dt.strftime('Q%q')
print (order)
  Order Date Quarter
0 2017-04-03      Q2
1 2017-09-20      Q3
2 2018-03-09      Q1
3 2018-08-26      Q3
4 2019-02-12      Q1
5 2019-08-01      Q3
6 2020-01-18      Q1
7 2020-07-06      Q3
8 2020-12-23      Q4
9 2021-06-11      Q2

My solution would be as follows:

order['Quarter'] = "Q" + order["Qtr"].astype("str")

This basically casts your numeric values to string and concatenates them with Q in front of it.

Alternatively you can just map arbitrary conversion functions like so:

order['Qtr'] = pd.to_datetime(order['Order Date']).dt.quarter
order['Quarter'] = df.map(lambda q: f"Q{q}")

Note that this uses F-strings which I believe requires python 3.6+

Related