python - Pandas :计算时间范围内的平均值

标签 python python-3.x pandas

我正在处理如下所示的大型数据集:

Time,   Value
01.01.2018 00:00:00.000,  5.1398
01.01.2018 00:01:00.000,  5.1298
01.01.2018 00:02:00.000,  5.1438
01.01.2018 00:03:00.000,  5.1228
01.01.2018 00:04:00.000,  5.1168
.... , ,,,,
31.12.2018 23:59:59.000,  6.3498

数据是从一年的第一天到一年的最后一天分钟数据

我想使用 Pandas 计算每 5 天的平均值。

例如:

01.01.2018 00:00:00.00005.01.2018 23:59:59.000 的平均值是 05.01.2018 的平均值/p>

下一个平均值将从 02.01.2018 00:00:00.0006.01.2018 23:59:59.00006.01.2018< 的平均值

下一个平均值将从 03.01.2018 00:00:00.0007.01.2018 23:59:59.00007.01.2018< 的平均值

依此类推...我们将日递增 1,但会计算从这一天到过去 5 天(包括当前日期)的平均值。

For a given day, there are 24hours * 60minutes = 1440 data points. So I need to get the average of 1440 data points * 5 days = 7200 data points.

最终的 DataFrame 将如下所示,时间格式为 [DD.MM.YYYY](没有 hh:mm:ss),Value 是包括当前日期在内的 5 个数据的平均值:

Time,   Value
05.01.2018,  5.1398
06.01.2018,  5.1298
07.01.2018,  5.1438
.... , ,,,,
31.12.2018,  6.3498

底线是计算从今天到过去5天的数据的平均值,平均值如上所示。

我尝试通过 Python 循环进行迭代,但我想要比 Pandas 更好的东西。

最佳答案

也许这会奏效?

import numpy as np

# Create one year of random data spaced evenly in 1 minute intervals.
np.random.seed(0)  # So that others can reproduce the same result given the random numbers.
time_idx = pd.date_range(start='2018-01-01', end='2018-12-31', freq='min')
df = pd.DataFrame({'Time': time_idx, 'Value': abs(np.random.randn(len(time_idx))) + 5})

>>> df.shape
(524161, 2)

给定间隔为 1 分钟的数据帧,您可以对过去五天(5 天 * 24 小时/天 * 60 分钟/小时 = 7200 分钟)进行滚动平均,并将结果分配给名为 rolling_5d_avg。然后,您可以使用 dt 访问器方法对原始时间戳进行分组以获取日期,然后获取每个日期的最后一个 rolling_5d_avg 值。

df = (
    df
    .assign(rolling_5d_avg=df.rolling(window=5*24*60)['Value'].mean())
    .groupby(df['Time'].dt.date)['rolling_5d_avg']
    .last()
)

>>> df.head(10)
Time
2018-01-01         NaN
2018-01-02         NaN
2018-01-03         NaN
2018-01-04         NaN
2018-01-05    5.786603
2018-01-06    5.784011
2018-01-07    5.790133
2018-01-08    5.786967
2018-01-09    5.789944
2018-01-10    5.789299
Name: rolling_5d_avg, dtype: float64

关于python - Pandas :计算时间范围内的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56799334/

相关文章:

python - 具有 Iterable 字段的卡住和可散列数据类

python - 使用 Python 读取 16 位 PNG 图像文件

python - 如何使用 Python 从 Windows 中的视频文件获取标题属性

python - Py_FindMethod 在 python3 中消失了。我应该用什么代替?

python - 根据条件对数据帧行进行分组和平均

python - 将 bool 数据框中的所有 True 替换为单元格位置

Python扩展小数

python - 尝试生成介于两者之间的 "-"的随 secret 码

python - 当列匹配时过滤来自两个 pandas DataFrame 的数据

python - matplotlib 中的透明 axes.axhline?