假设我有 1 个主烤箱,由 3 个子烤箱组成,编号分别为 1、2 和 3:
df = pd.DataFrame({
"sub_oven_number": [1,2,3,1,2,3],
"end_temp": ["700", "650", "630", "720", "650", "800"],
"end_temp_registration": ["2022-01-04", "2022-01-05", "2022-01-06", "2022-01-07", "2022-01-08", "2022-01-09"]
})
当烤箱准备就绪时,将记录 end_temp。现在我想计算三个子烤箱在任何时候的平均 end_temp 。在本例中,首先取前三个烤箱的平均值,即(700+650+630)/3。然后烤箱 1 正在重新填充。现在平均值是 (650,630,720)/3 等等。
另一个情况是,有时只有两个烤箱在运行,而有一个烤箱被跳过。因此,您不能简单地取最近三个观察值的平均值。
很难用文字解释我的问题,所以如果我需要澄清更多,请告诉我
IIUC,你想要某种或滚动平均值,但根据烤箱编号没有重复。
为此,我们可以使用 numpy 的
sliding_window_view
执行自定义滚动并制作掩模:
from numpy.lib.stride_tricks import sliding_window_view as swv
df['end_temp'] = df['end_temp'].astype(int)
N = 3
tmp1 = pd.DataFrame(swv(df['sub_oven_number'], N), index=df.index[N-1:])
tmp2 = pd.DataFrame(swv(df['end_temp'], N), index=df.index[N-1:])
mask = tmp1.apply(lambda x: x.duplicated(), axis=1)
df['mean'] = tmp2.mask(mask).mean(axis=1)
输出(稍微改变输入):
sub_oven_number end_temp end_temp_registration mean
0 1 700 2022-01-04 NaN
1 2 650 2022-01-05 NaN
2 3 630 2022-01-06 660.000000
3 1 720 2022-01-07 666.666667
4 2 650 2022-01-08 666.666667
5 1 800 2022-01-09 685.000000