Issue
I have a dataframe shown below
df = pd.DataFrame(
{'stud_id' : [101, 101, 101, 101,
101, 101, 101, 101],
'ques_date' : ['13/11/2020', '10/1/2018','11/11/2017', '27/03/2016',
'13/05/2010', '10/11/2008','11/1/2007', '27/02/2006']})
Basically, I would like to do the below
a) Get the fiscal quarter for each ques_date
However, our company follows their own definition for quarter which is given below
Q1 - Oct to Dec
Q2 - Jan to Mar
Q3 - Apr to Jun
Q4 - July - Sep
I was trying something like below
df['act_qtr'] = df['ques_date'].dt.to_period('Q')
df['custom_qtr'] = np.where(df['act_qtr'] == 'Q1','Q2',(df['act_qtr'] == 'Q2', 'Q3',(df['act_qtr'] == 'Q3', 'Q4', (df['act_qtr'] == 'Q4', 'Q1'))))
But this is not elegant and efficient.
Is there any pythonic or better way to do this?
I expect my output to be like below
Solution
One idea is add 1 for next quarter, then use Series.dt.strftime
for custom string Q1, Q2, Q3, Q4
:
df['ques_date'] = pd.to_datetime(df['ques_date'], dayfirst=True)
df['act_qtr'] = df['ques_date'].dt.to_period('Q').add(1).dt.strftime('Q%q')
print (df)
stud_id ques_date act_qtr
0 101 2020-11-13 Q1
1 101 2018-01-10 Q2
2 101 2017-11-11 Q1
3 101 2016-03-27 Q2
4 101 2010-05-13 Q3
5 101 2008-11-10 Q1
6 101 2007-01-11 Q2
7 101 2006-02-27 Q2
Answered By - jezrael
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.