I would like to convert my date column into an indicator of the quarter of that particular year, say 2018q1
or 2018q2
etc.
My data looks like this, I have stock returns once per quarter (not showing the return column here), and a corresponding date, the column quarter is what I would like to get (or something similar)
data = [{'date': '3/22/18', 'quarter': 1},{'date': '3/22/18', 'quarter': 1},
{'date': '6/22/18', 'quarter': 3},{'date': '6/22/18', 'quarter': 3},
{'date': '9/22/18', 'quarter': 2},{'date': '9/22/18', 'quarter': 2}]
df = pd.DataFrame(data, index=['s1', 's2','s1','s2','s1','s2'])
date quarter
s1 3/22/13 2013q1
s2 3/24/13 2013q1
s1 6/21/13 2013q2
s2 6/26/13 2013q2
s1 9/21/13 2013q3
s2 9/28/13 2013q3
date, (x. month-1)//3 will give you the quarter (0 for first quarter, 1 for second quarter, etc -- add 1 if you need to count from 1 instead;-).
For this, we will use the strptime() method and Pandas module. This method is used to create a DateTime object from a string. Then we will extract the date from the DateTime object using the date() function and dt. date from Pandas in Python.
to_datetime(x['Mth']. values). astype('period[Q]') works, but pd. to_datetime(x['Mth']).
To format and return the string representation of the Period object, use the period. strftime() method. With that, set the format specifiers as an argument like strftime('%d-%b-%Y').
to_datetime
:
df.date = pd.to_datetime(df.date)
PeriodIndex
df['quarter'] = pd.PeriodIndex(df.date, freq='Q')
date quarter
s1 2018-03-22 2018Q1
s2 2018-03-22 2018Q1
s1 2018-06-22 2018Q2
s2 2018-06-22 2018Q2
s1 2018-09-22 2018Q3
s2 2018-09-22 2018Q3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With