通过求和降低阵列的分辨率

fra*_*xel 11 python numpy

如果我有这样的数组:

a = np.array([[ 1, 2, 3, 4],
              [ 5 ,6, 7, 8],
              [ 9,10,11,12],
              [13,14,15,16]])
Run Code Online (Sandbox Code Playgroud)

我想'改变分辨率',最后得到一个更小的数组(比如2行乘2列,或2行乘4列等).我想通过求和来改变这种分辨率.我需要这个来处理大型数组,较小数组的行数,cols将始终是较大数组的一个因素.

将上面的数组减少到2乘2的数组会导致(这就是我想要的):

[[ 14.  22.]
 [ 46.  54.]]
Run Code Online (Sandbox Code Playgroud)

我有这个功能,它做得很好:

import numpy as np

def shrink(data, rows, cols):
    shrunk = np.zeros((rows,cols))
    for i in xrange(0,rows):
        for j in xrange(0,cols):
            row_sp = data.shape[0]/rows
            col_sp = data.shape[1]/cols
            zz = data[i*row_sp : i*row_sp + row_sp, j*col_sp : j*col_sp + col_sp]
            shrunk[i,j] = np.sum(zz)
    return shrunk

print shrink(a,2,2)
print shrink(a,2,1)
#correct output:
[[ 14.  22.]
 [ 46.  54.]]
[[  36.]
 [ 100.]]
Run Code Online (Sandbox Code Playgroud)

我已经仔细研究了这些例子,但似乎找不到任何有用的东西.

有没有更快的方法来做到这一点,而不需要循环?

eum*_*iro 24

用你的例子:

a.reshape(2,2,2,2).sum(axis=1).sum(axis=2)
Run Code Online (Sandbox Code Playgroud)

收益:

array([[14, 22],
       [46, 54]])
Run Code Online (Sandbox Code Playgroud)

现在让我们创建一个通用函数......

def shrink(data, rows, cols):
    return data.reshape(rows, data.shape[0]/rows, cols, data.shape[1]/cols).sum(axis=1).sum(axis=2)
Run Code Online (Sandbox Code Playgroud)

适用于您的示例:

In [19]: shrink(a, 2,2)
Out[19]: 
array([[14, 22],
       [46, 54]])

In [20]: shrink(a, 2,1)
Out[20]: 
array([[ 36],
       [100]])
Run Code Online (Sandbox Code Playgroud)