如何在Python中将日期转换为四分之一? [英] How to convert dates to quarters in Python?
本文介绍了如何在Python中将日期转换为四分之一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将日期列转换为该特定年份的季度指标,例如 2018q1
或 2018q2
等.
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
推荐答案
to_datetime
:
to_datetime
:
df.date = pd.to_datetime(df.date)
PeriodIndex
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
这篇关于如何在Python中将日期转换为四分之一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文