gpt4 book ai didi

python - 3D 数组中一个轴上的滚动平均值

转载 作者:行者123 更新时间:2023-12-04 03:55:50 24 4
gpt4 key购买 nike

有没有一种简单的方法可以计算 3D 数组中一个轴上的滚动平均值?假设我有一个包含 x、y 和时间轴的数组,我想要所有 x 和 y 在时间轴上的滚动平均值。对于一维数组,我使用 pandas:

import pandas as pd 

rolling_array = pd.Series(array).rolling(window=window).mean()

但这不适用于多维数据。

编辑:

我的数组看起来像这样:

import numpy as np 

array = np.random.rand(100,100,200)

我想要 axis = 2

的滚动平均值

最佳答案

我们可以使用uniform_filter1d接受 axis arg,我们将使它通用以接受沿通用轴的任何 n-dim 数组 -

from scipy.ndimage import uniform_filter1d

def rolling_mean_along_axis(a, W, axis=-1):
# a : Input ndarray
# W : Window size
# axis : Axis along which we will apply rolling/sliding mean
hW = W//2
L = a.shape[axis]-W+1
indexer = [slice(None) for _ in range(a.ndim)]
indexer[axis] = slice(hW,hW+L)
return uniform_filter1d(a,W,axis=axis)[tuple(indexer)]

验证形状的样本运行:

In [70]: a = np.random.rand(10,10,10)

In [72]: rolling_mean_along_axis(a, W=5, axis=0).shape
Out[72]: (6, 10, 10)

In [73]: rolling_mean_along_axis(a, W=5, axis=1).shape
Out[73]: (10, 6, 10)

In [74]: rolling_mean_along_axis(a, W=5, axis=2).shape
Out[74]: (10, 10, 6)

关于python - 3D 数组中一个轴上的滚动平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63934520/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com