我正在处理如下所示的大型数据集:
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.000
到 05.01.2018 23:59:59.000
的平均值是 05.01.2018
的平均值/p>
下一个平均值将从 02.01.2018 00:00:00.000
到 6.01.2018 23:59:59.000
是 06.01.2018< 的平均值
下一个平均值将从 03.01.2018 00:00:00.000
到 7.01.2018 23:59:59.000
是 07.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/