简体   繁体   English

减少 numpy 数组的第三维并对值求和

[英]Reduce 3rd dimension of numpy array and sum the values

I think this is straightforward but I can't quite get it.我认为这很简单,但我不太明白。 I have a large 3d array and I want to reduce the 3rd dim by some factor and then sum the values to get to that reduced size.我有一个大型 3d 阵列,我想将第三个暗淡减少一些因素,然后将这些值相加以达到减小的大小。 An example that works to get what I want is:一个可以得到我想要的例子是:

import numpy as np

arr=np.ones((10,10,16))
processed_data=np.zeros((arr.shape[0], arr.shape[1]), dtype='object')
factor=2

for i in range(arr.shape[0]):
    for j in range(arr.shape[1]):
        processed_data[i][j]=arr[i][j].reshape(int(arr.shape[2]/factor),-1).sum(axis=1)

So we take the last dimension, reshape it to an extra dimension and then sum along that dimension.所以我们取最后一个维度,将其重塑为一个额外的维度,然后沿该维度求和。 In the example above the data is a 10x10x16 array of all 1s so with a factor=2 we get a 10x10x8 array out with the data all being 2s.在上面的示例中,数据是一个全为 1 的 10x10x16 数组,因此当因子 = 2 时,我们得到一个 10x10x8 数组,其中数据全为 2。 I hope this illustrates what I am trying to achieve.我希望这能说明我正在努力实现的目标。 If the factor would change to 4 we would get a 10x10x4 array out.如果因子变为 4,我们将得到一个 10x10x4 的数组。

This method is not ideal as it involves creating a separate processed_data 'object' array where I would rather leave it as a 3D array, just with a reduced third dimension.这种方法并不理想,因为它涉及创建一个单独的处理数据“对象”数组,我宁愿将其保留为 3D 数组,只是减少了第三维。 It also involves iterating over every element in the 2D array which I don't think is neccessary.它还涉及迭代 2D 数组中的每个元素,我认为这是不必要的。 And it's really slow.而且真的很慢。

Any help appreciated - I suspect it is a combination of reshaping and transposing but cannot get my head around it.任何帮助表示赞赏 - 我怀疑它是重塑和转置的组合,但我无法理解它。

Thanks.谢谢。

I think you can reshape on the whole data and sum:我认为您可以重塑整个数据并求和:

arr.reshape(*arr.shape[:2], -1, 2).sum(axis=-1)

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

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