Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

pandas - How to convert dates to quarters in Python?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...