python - 在 Pandas 中获取平均年份(多年平均天数)

标签 python datetime numpy pandas time-series

我是 Pandas 时间序列和数据框的新手,很难完成这个简单的任务。 从 2004 年 1 月 1 日到 2008 年 12 月 31 日,我每天都有一个数据集“数据”(一维 float32-Numpy 数组)。日期存储为日期时间对象“日期”列表。 基本上,我想计算一个完整的“标准年”——所有年份(1-365)中每一天的平均值。 我从这个类似的(?)问题(Getting the average of a certain hour on weekdays over several years in a pandas dataframe)开始,但无法得到想要的结果 - 365 个“平均”天的时间序列,例如所有四个 1 月 1 日、1 月 2 日的平均值...

一个小示例脚本:

import numpy as np
import pandas as pd
import datetime

startdate = datetime.datetime(2004, 1, 1)
enddate = datetime.datetime(2008, 1, 1)
days = (enddate + datetime.timedelta(days=1) - startdate).days
data = np.random.random(days)
dates = [startdate + datetime.timedelta(days=x) for x in range(0, days)]

ts = pd.Series(data, dates)
test = ts.groupby(lambda x: (x.year, x.day)).mean()

最佳答案

和日分组,而不是年和日:

test = ts.groupby([ts.index.month, ts.index.day]).mean()

产量

1  1     0.499264
   2     0.449357
   3     0.498883
...
12  17    0.408180
    18    0.317682
    19    0.467238
...    
    29    0.413721
    30    0.399180
    31    0.828423
Length: 366, dtype: float64

关于python - 在 Pandas 中获取平均年份(多年平均天数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28304881/

相关文章:

c# - 弄清楚这个日期格式

python - 快速 python 算法(在 numpy 或 pandas 中?)查找与另一个数组中的元素匹配的数组元素的索引

python - cx_Oracle 插入大 XMLType 值

python - 如何组合不同 channel 的图像?

python - 将月份添加到 Pandas 中的日期

php - 使用 Carbon 将时间字段添加到当前日期字段

sql - Postgresql 串行每日记录计数

python - 将 NaN 添加到 pandas 系列时,保留 bool 和 float 之间的区别?

python - 在numpy中将一维数组转换为二维数组

Python:libc fallocate 返回失败