沿不相交索引的NumPy总和 [英] NumPy sum along disjoint indices

查看:51
本文介绍了沿不相交索引的NumPy总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,需要对3D NumPy数组中的任意索引组求和.内置的NumPy数组求和例程将ndarray维度之一上的所有索引求和.相反,我需要对数组中某一维度的索引范围求和,然后返回一个新数组.

I have an application where I need to sum across arbitrary groups of indices in a 3D NumPy array. The built-in NumPy array sum routine sums up all indices along one of the dimensions of an ndarray. Instead, I need to sum up ranges of indices along one of the dimensions in my array and return a new array.

例如,假设我有一个形状为(70,25,3)的ndarray.我希望总结某些索引范围内的第一个维度,并返回一个新的3D数组.考虑来自0:25, 25:5050:75的总和,它们将返回形状为(3,25,3)的数组.

For example, let's assume that I have an ndarray with shape (70,25,3). I wish to sum up the first dimension along certain index ranges and return a new 3D array. Consider the sum from 0:25, 25:50 and 50:75 which would return an array of shape (3,25,3).

是否有一种简单的方法可以沿NumPy数组的一维进行不相加和"以产生此结果?

Is there an easy way to do "disjoint sums" along one dimension of a NumPy array to produce this result?

推荐答案

您可以使用np.add.reduceat作为解决此问题的常规方法.即使范围的长度不尽相同,也可以使用.

You can use np.add.reduceat as a general approach to this problem. This works even if the ranges are not all the same length.

要对沿轴0的切片0:2525:5050:75求和,请传入索引[0, 25, 50]:

To sum the slices 0:25, 25:50 and 50:75 along axis 0, pass in indices [0, 25, 50]:

np.add.reduceat(a, [0, 25, 50], axis=0)

此方法也可以用于对非连续范围求和.例如,要对切片0:2537:4751:75求和,请写:

This method can also be used to sum non-contiguous ranges. For instance, to sum the slices 0:25, 37:47 and 51:75, write:

np.add.reduceat(a, [0,25, 37,47, 51], axis=0)[::2]

相同长度的范围求和的另一种方法是对数组进行整形,然后沿轴求和.等同于上面的第一个示例:

An alternative approach to summing ranges of the same length is to reshape the array and then sum along an axis. The equivalent to the first example above would be:

a.reshape(3, a.shape[0]//3, a.shape[1], a.shape[2]).sum(axis=1)

这篇关于沿不相交索引的NumPy总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆