7

假设我有以下数组:

a = np.array([[1,2,3,4,5,6], 
              [7,8,9,10,11,12],
              [3,5,6,7,8,9]])

我想对第一行的前两个值求和:1+2 = 3,然后是接下来的两个值:3+4 = 7,然后5+6 = 11是 ,依此类推。我想要的输出是这样的:

array([[ 3,  7, 11],
       [15, 19, 23],
       [ 8, 13, 17]])

我有以下解决方案:

def sum_chunks(x, chunk_size):
    rows, cols = x.shape
    x = x.reshape(x.size / chunk_size, chunk_size)
    return x.sum(axis=1).reshape(rows, cols/chunk_size)

但是感觉不必要的复杂,有没有更好的方法?也许是内置的?

4

3 回答 3

7

只需使用切片:

a[:,::2] + a[:,1::2]

这获取由每个偶数索引列 ( ::2) 形成的数组,并将其添加到由每个奇数索引列 ( 1::2) 形成的数组中。

于 2013-09-03T00:57:50.750 回答
6

当我必须做这种事情时,我更喜欢将 2D 数组重塑为 3D 数组,然后用np.sum. 将其推广到 n 维数组,您可以执行以下操作:

def sum_chunk(x, chunk_size, axis=-1):
    shape = x.shape
    if axis < 0:
        axis += x.ndim
    shape = shape[:axis] + (-1, chunk_size) + shape[axis+1:]
    x = x.reshape(shape)
    return x.sum(axis=axis+1)

>>> a = np.arange(24).reshape(4, 6)
>>> a
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]])
>>> sum_chunk(a, 2)
array([[ 1,  5,  9],
       [13, 17, 21],
       [25, 29, 33],
       [37, 41, 45]])
>>> sum_chunk(a, 2, axis=0)
array([[ 6,  8, 10, 12, 14, 16],
       [30, 32, 34, 36, 38, 40]])
于 2013-09-03T02:33:51.820 回答
1

这是一种方法:

>>> a[:,::2] + a[:,1::2]
array([[ 3,  7, 11],
       [15, 19, 23],
       [ 8, 13, 17]])
于 2013-09-03T00:57:49.407 回答