如果我有每个月的值,我如何计算python中的季度平均值?

时间:2018-04-11 09:17:51

标签: python-3.x pandas dataframe

State/Territory Date    Employment Rate (15-64) Unemployment Rate (15+)
NSW 1978-02-01  n/a     6.8
NSW 1978-03-01  n/a     6.5
NSW 1978-04-01  63.7    6.5
NSW 1978-05-01  63.7    6.1
NSW 1978-06-01  63.7    6.4
NSW 1978-07-01  63.7    6.1
NSW 1978-08-01  63.5    6.3
NSW 1978-09-01  63.5    6.3
NSW 1978-10-01  63.5    6.1
NSW 1978-11-01  63.5    6.2
NSW 1978-12-01  63.8    6.0
NSW 1979-01-01  63.4    5.9
NSW 1979-02-01  63.5    5.9
NSW 1979-03-01  63.3    6.2
NSW 1979-04-01  63.5    6.4
NSW 1979-05-01  63.3    6.2
NSW 1979-06-01  63.2    6.2
NSW 1979-07-01  63.3    6.2
NSW 1979-08-01  63.4    5.5
NSW 1979-09-01  63.7    5.6
NSW 1979-10-01  63.9    5.9
NSW 1979-11-01  64.3    5.5

这是我的数据,现在我想计算每个州每个季度的平均失业率。有办法吗?

1 个答案:

答案 0 :(得分:2)

date转换为日期时间类型提取quarter,然后转换为groupby

In [7]: df['Date'] = pd.to_datetime(df['Date'])
In [10]: df['quarter'] = df.Date.dt.quarter

In [11]: df.groupby(['quarter','State/Territory'])['UnemploymentRate(15+)'].mean()
Out[11]: 
quarter  State/Territory
1        NSW                6.26
2        NSW                6.30
3        NSW                6.00
4        NSW                5.94
Name: UnemploymentRate(15+), dtype: float64