pandas 如何在 Python 中将日期转换为季度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50459301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert dates to quarters in Python?
提问by Niccola Tartaglia
I would like to convert my date column into an indicator of the quarter of that particular year, say 2018q1
or 2018q2
etc.
我想将我的日期列转换为该特定年份的季度指标,例如2018q1
或2018q2
等等。
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
回答by user3483203
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
回答by ????g?ň?c????
Just extract the month part of your date string. The quarter can simply be obtained through month // 4 + 1
.
只需提取日期字符串的月份部分。季度可以简单地通过获得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.
由于您的数据是一个字典,其'date'
键是 astr
形式(\d{1:2})/(\d{1:2})/(\d\d)
,您可以获取日期的“月份”部分(第一组),将其转换为 int,并用于month // 4 + 1
获取季度。
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:
可以使用正则表达式甚至简单的字符串切片来提取日期字符串的月份部分。因此,季度范围从 1 到 4,由以下因素决定:
m // 4
is 0 for1 <= m <= 3
(Q1)m // 4
is 1 for4 <= m <= 6
(Q1)m // 4
is 2 for7 <= m <= 9
(Q1)m // 4
is 3 for10 <= m <= 12
(Q1)
m // 4
1 <= m <= 3
(Q1)为 0m // 4
4 <= m <= 6
(Q1)为 1m // 4
7 <= m <= 9
(Q1)为 2m // 4
10 <= m <= 12
(Q1)为 3
回答by Kush Modi
.date will not work as it is a function of data frame.
.date 将不起作用,因为它是数据框的函数。
df_q8['Date'] = pd.to_datetime(df_q8['Date'])
df_q8['quarter'] = pd.PeriodIndex(df_q8['Date'] ,freq='Q')
回答by haritha c
datecolumn.dt.quarter
feature will help.
datecolumn.dt.quarter
功能会有所帮助。
df.date = pd.to_datetime(df.date)
df["Quarter"] = df.date.dt.quarter