简体   繁体   English

numpy.array的部分内容

[英]sum parts of numpy.array

Let's say I have the following array: 假设我有以下数组:

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

I want to sum the first two values of the first row: 1+2 = 3 , then next two values: 3+4 = 7 , and then 5+6 = 11 , and so on for every row. 我想总结第一行的前两个值: 1+2 = 3 ,然后接下来的两个值: 3+4 = 7 ,然后5+6 = 11 ,依此类推每一行。 My desired output is this: 我想要的输出是这样的:

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

I have the following solution: 我有以下解决方案:

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)

But it feels unnecessarily complicated, is there a better way? 但感觉不必要的复杂,有更好的方法吗? Perhaps a built-in? 也许内置?

Just use slicing: 只需使用切片:

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

This takes the array formed by every even-indexed column ( ::2 ), and adds it to the array formed by every odd-indexed column ( 1::2 ). 这将获取由每个偶数索引列( ::2 )形成的数组,并将其添加到由每个奇数索引列( 1::2 )形成的数组中。

When I have to do this kind of stuff, I prefer reshaping the 2D array into a 3D array, then collapse the extra dimension with np.sum . 当我必须做这种事情时,我更喜欢将2D阵列重塑为3D阵列,然后使用np.sum折叠额外的维度。 Generalizing it to n-dimensional arrays, you could do something like this: 将其推广到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]])

Here's one way: 这是一种方式:

>>> a[:,::2] + a[:,1::2]
array([[ 3,  7, 11],
       [15, 19, 23],
       [ 8, 13, 17]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM