[英]How can I add to each element of a numpy ndarray the sum of all its index values with python ?
I have a numpy ndarray, let's take an example (but it can be totally different): 我有一个numpy ndarray,让我们举个例子(但可以完全不同):
[[[0 0 0]
[1 1 1]
[0 0 0]]
[[1 0 1]
[1 0 1]
[1 0 1]]]
[[1 0 0]
[1 1 0]
[1 1 1]]]
I want to add to each element the sum of its indexes in all dimensions. 我想将每个维度的索引总和添加到每个元素。 The result here would be:
结果将是:
[[[ 0 1 2]
[ 4 5 6]
[ 6 7 8]]
[[10 10 12]
[13 13 15]
[16 16 18]]
[[19 19 20]
[22 23 23]
[25 26 27]]]
To do so, I built another ndarray: 为此,我构建了另一个ndarray:
shp = a.shape
b = np.arange(shp[0]**len(shp)).reshape(shp)
And I got my result: 我得到了我的结果:
result = a+b
I would like to know if there is a more direct solution, which wouldn't need the creation of this second ndarray, a way to do the same operation 'on location' ?? 我想知道是否有一个更直接的解决方案,它不需要创建第二个ndarray,一种在“位置”上执行相同操作的方法?
Simply create open grids, that are basically 1D arrays extended to more dims and add into input array leveraging broadcasting
- 只需创建开放式网格即可,基本上是一维阵列,扩展到更多的暗点,然后利用
broadcasting
将其添加到输入阵列中-
m,n,r = a.shape
I,J,K = np.ogrid[:m,:n,:r]
out = a + I*n*r + J*r + K
Hence, in terms of memory occupancy, we are creating only 9 (=m+n+r) more elements as opposed to 27 (= m * n * r) elements with the range-based
soltuion. 因此,就内存占用而言,与
range-based
相比,我们只创建了9(= m + n + r)个元素,而不是27(= m * n * r)个元素。
Sample run - 样品运行-
In [41]: a
Out[41]:
array([[[0, 0, 0],
[1, 1, 1],
[0, 0, 0]],
[[1, 0, 1],
[1, 0, 1],
[1, 0, 1]],
[[1, 0, 0],
[1, 1, 0],
[1, 1, 1]]])
In [42]: m,n,r = a.shape
In [43]: I,J,K = np.ogrid[:m,:n,:r]
In [44]: a + I*n*r + J*r + K
Out[44]:
array([[[ 0, 1, 2],
[ 4, 5, 6],
[ 6, 7, 8]],
[[10, 10, 12],
[13, 13, 15],
[16, 16, 18]],
[[19, 19, 20],
[22, 23, 23],
[25, 26, 27]]])
N-dim array case N维阵列盒
For a generic n-dim array, a
to add into itself - 对于通用n维数组,将
a
添加到自身中-
shp = a.shape
grid = np.ogrid[tuple(map(slice, shp))]
scale = np.r_[np.array(shp)[::-1].cumprod()[::-1][1:],1]
for i,j in zip(grid,scale):
a += i*j
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.