python - Pandas 系列的多月平均值

标签 python pandas time-series

我有一系列 datetime 对象和一系列跨越数年的数据。 A 可以创建一个 Series 对象并对其重新采样以按月对其进行分组:

df=pd.Series(varv,index=dates)
multiMmean=df.resample("M", how='mean')
print multiMmean

然而,这会输出

2005-10-31    172.4
2005-11-30     69.3
2005-12-31    187.6
2006-01-31    126.4
2006-02-28    187.0
2006-03-31    108.3
...
2014-01-31     94.6
2014-02-28     82.3
2014-03-31    130.1
2014-04-30     59.2
2014-05-31     55.6
2014-06-30      1.2

这是该系列每个月的平均值列表。这不是我想要的。我想要 12 个值,一个代表一年中的每个月,一个代表多年来的每个月。我如何为 multiMmean 获取它?

我已经尝试在 multiMmean 上使用 resample("M",how='mean') 和列表理解,但我无法让它工作。我错过了什么?

谢谢。

最佳答案

以下对我有用:

# create some random data with datetime index spanning 17 months
s = pd.Series(index=pd.date_range(start=dt.datetime(2014,1,1), end = dt.datetime(2015,6,1)), data = np.random.randn(517))

In [25]:
# now calc the mean for each month
s.groupby(s.index.month).mean()
Out[25]:
1     0.021974
2    -0.192685
3     0.095229
4    -0.353050
5     0.239336
6    -0.079959
7     0.022612
8    -0.254383
9     0.212334
10    0.063525
11   -0.043072
12   -0.172243
dtype: float64

因此我们可以groupby datetimeindex 的month 属性并调用mean 这将计算所有月份的平均值

关于python - Pandas 系列的多月平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30109522/

相关文章:

pandas - 如何使用 pandas 转换 df

python - 按 Pandas 组顺序计算差异

python - Linkedin Luminol 异常检测和关联库的工作示例

python - “继续” 'for' 循环到前一个元素

python - 在 python 中为 Hadoop Map Reduce 创建自定义可写键/值类型?

python - 如何从 pytest 注入(inject) pygame 事件?

python - 如何将 datetime.time() 对象转换为 datetime.datetime 对象 pandas

python - 使用字典值在两个日期之间进行 Pandas Dataframe 查询

mysql - 根据时间从多个表中获取最接近数据的最快方法

python - Office365-REST-Python-客户端访问 token 问题