How to convert dates to quarters in Python?

可紊 提交于 2020-12-30 07:33:18

问题


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

回答1:


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



回答2:


Just extract the month part of your date string. The quarter can simply be obtained through month // 4 + 1.

Since your data is a dictionary whose 'date' key is a str of form (\d{1:2})/(\d{1:2})/(\d\d), you can get the "month" part of the date (the first group), convert it to an int, and use month // 4 + 1 to get the quarter.

Extracting the month part of the date string can be done using regex or even simple string slicing. The quarter therefore ranges from 1 to 4 and is determine by:

  • m // 4 is 0 for 1 <= m <= 3 (Q1)
  • m // 4 is 1 for 4 <= m <= 6 (Q1)
  • m // 4 is 2 for 7 <= m <= 9 (Q1)
  • m // 4 is 3 for 10 <= m <= 12 (Q1)



回答3:


datecolumn.dt.quarter feature will help.

df.date = pd.to_datetime(df.date)
df["Quarter"] = df.date.dt.quarter



回答4:


.date will not work as it is a function of data frame.

df_q8['Date'] = pd.to_datetime(df_q8['Date'])
df_q8['quarter'] = pd.PeriodIndex(df_q8['Date'] ,freq='Q')


来源:https://stackoverflow.com/questions/50459301/how-to-convert-dates-to-quarters-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!