随着时间的推移,我无法获得平均值。我有一个特定时间的传感器读数列表,我想获得传感器值的每小时平均值。 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 Sensor1TS 2010-01-02 11:58:00 02010-01-02 12:30:00 12010-01-02 13:05:00 1212010-01-02 13:06:00 12010-01-02 14:30:00 2 Sensor1 min max mean count mymeanTS 2010-01-02 11:00:00 0 0 0 1 NaN2010-01-02 12:00:00 1 1 1 1 0.52010-01-02 13:00:00 1 121 61 2 3.02010-01-02 14:00:00 2 2 2 1 1.5我可以对采样频率进行上采样ffill并取平均值,但这看起来效率很低。
1 回答
倚天杖
TA贡献1828条经验 获得超3个赞
我是这样做的:
添加行标记每个组的开头,给它们值ffill:
extra_times = pandas.date_range(t_0, periods=3, freq='1H')
pdf_reindexed = (pandas
.concat([pdf_query, pandas.DataFrame(index=extra_times)], sort=False)
.sort_index()
.ffill()
)
添加差异列span:
timestamp = pdf_reindexed.index.to_series()
pdf_reindexed["span"] = (timestamp.shift(-1) - timestamp).dt.seconds
乘以:value_span
pdf_reindexed["product"] = pdf_reindexed["span"] * pdf_reindexed["Sensor1"]
聚合和分割:
pdf_time_mean = (pdf_reindexed
.resample("1H")
.agg({"product": "sum"})
)
pdf_time_mean["product"] = pdf_time_mean["product"] / 3600
添加回答
举报
0/150
提交
取消