随着时间的推移,我无法获得平均值。
我有一个特定时间的传感器读数列表,我想获得传感器值的每小时平均值。
from datetime import datetime, timedelta
import numpy
import pandas
key_id = 1234
key_label = "Sensor1"
t_0 = datetime(2010,1,2,12)
data = [
[t_0 - timedelta(seconds=120), key_id, 0],
[t_0 + timedelta(seconds=1800), key_id, 1],
[t_0 + timedelta(seconds=3600 + 300), key_id, 121],
[t_0 + timedelta(seconds=3600 + 360), key_id, 1],
[t_0 + timedelta(seconds=7200 + 1800), key_id, 2],
]
df = pandas.DataFrame(list(map(lambda r: list(r), data)), columns=["TS", "KeyId", "Value"])
df_pivot = (df
.pivot(index="TS", columns="KeyId", values="Value")
.ffill()
.rename({key_id: key_label}, axis='columns')
)
def mymean(*args, **kwargs):
expected_results = [numpy.NaN, 0.5, 3, 1.5]
d0 = args[0].index[0]
if d0 == data[0][0]:
return expected_results[0]
if d0 == data[1][0]:
return expected_results[1]
if d0 == data[2][0]:
return expected_results[2]
if d0 == data[4][0]:
return expected_results[3]
return "???"
results = (df_pivot
.resample('1H')
.agg(["min", "max", "mean", "count", mymean])
)
display(df_pivot)
display(results)
预期结果在列中mymean。13:00 到 14:00 之间有两个值。这两个值的平均值为 61,但传感器仅停留在 121 分钟,因此预期平均值应为 3(对于懒惰的读者:(1*59 + 121*1) / 60)。
KeyId Sensor1
TS
2010-01-02 11:58:00 0
2010-01-02 12:30:00 1
2010-01-02 13:05:00 121
2010-01-02 13:06:00 1
2010-01-02 14:30:00 2
Sensor1
min max mean count mymean
TS
2010-01-02 11:00:00 0 0 0 1 NaN
2010-01-02 12:00:00 1 1 1 1 0.5
2010-01-02 13:00:00 1 121 61 2 3.0
2010-01-02 14:00:00 2 2 2 1 1.5
我可以对采样频率进行上采样ffill并取平均值,但这看起来效率很低。
倚天杖
相关分类