【问题标题】:Rolling mean over one axis in 3D-array在 3D 阵列中的一个轴上滚动平均值
【发布时间】:2020-09-17 08:51:32
【问题描述】:

有没有一种简单的方法来计算 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

【问题讨论】:

  • @Divakar np.mean 可以滚动窗口吗?
  • 哦,不是。我错过了。
  • 统一过滤器怎么样 - docs.scipy.org/doc/scipy/reference/generated/…
  • @HansHirse 我有一个 numpy 3D 数组,其中包含每个 x 和 y 坐标以及每个时间步长的降水值 - 所以它实际上是一个 3D 数组。
  • 熊猫系列是一维的。改用 DataFrame

标签: python arrays pandas numpy


【解决方案1】:

我们可以使用接受axis arg 的uniform_filter1d,我们将使其通用以接受沿通用轴的任何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)

【讨论】:

    猜你喜欢
    • 2021-08-07
    • 2018-05-11
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 2013-06-16
    • 1970-01-01
    • 2018-09-23
    相关资源
    最近更新 更多