以任意数量的维度对numpy数组进行子采样

时间:2016-04-18 11:06:15

标签: python arrays numpy

我有一个n - 维度numpy数组(n原则上未知,但实际上它是一个很小的数字,通常是n<=3)。我想在每个方向上对每个m条目进行子采样。所以对于2d数组,这将是

arr[::m, ::m]

有没有办法将其概括为任意n? (在实践中,我可以检查值并使用上面的不同版本,但我怀疑有一种更优雅的方式)。

1 个答案:

答案 0 :(得分:4)

使用切片:

In [1]: import numpy as np

In [2]: a = np.array(range(3*5*5)).reshape(3, 5, 5)

In [3]: a
Out[3]: 
array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14],
        [15, 16, 17, 18, 19],
        [20, 21, 22, 23, 24]],

       [[25, 26, 27, 28, 29],
        [30, 31, 32, 33, 34],
        [35, 36, 37, 38, 39],
        [40, 41, 42, 43, 44],
        [45, 46, 47, 48, 49]],

       [[50, 51, 52, 53, 54],
        [55, 56, 57, 58, 59],
        [60, 61, 62, 63, 64],
        [65, 66, 67, 68, 69],
        [70, 71, 72, 73, 74]]])

In [4]: a[::2, ::2, ::2]
Out[4]: 
array([[[ 0,  2,  4],
        [10, 12, 14],
        [20, 22, 24]],

       [[50, 52, 54],
        [60, 62, 64],
        [70, 72, 74]]])

In [5]: a[[slice(None, None, 2)] * a.ndim]
Out[5]: 
array([[[ 0,  2,  4],
        [10, 12, 14],
        [20, 22, 24]],

       [[50, 52, 54],
        [60, 62, 64],
        [70, 72, 74]]])