I have a 4D array 'a' of size (2,3,4,4) filled with zeros.
我有一个4D数组'a'大小(2,3,4,4)填充零。
import numpy as np
a = np.zeros((2,3,4,4))
I also have a 3D array 'b' of size(2,3,4) that carries some index values (all between 0 and 3).
我还有一个大小为(2,3,4)的3D数组'b',它带有一些索引值(全部在0和3之间)。
What I want to do is replace the element of every last array in 'a' (the 4th dimension of 'a') that corresponds to the index in 'b', with 1.
我想要做的是将'a'中的每个最后一个数组的元素('a'的第四个维度)替换为'b'中的索引,使用1。
I can do this with 3 for loops, as shown below:
我可以使用3 for循环执行此操作,如下所示:
for i in a.shape[0]:
for j in a.shape[1]:
for z in a.shape[2]:
a[i,j,z][b[i,j,z]] = 1
But I was wondering if there is anyway I can avoid looping at all. Something similar to:
但我想知道无论如何我都可以避免循环。类似于:
a[b] = 1
1 个解决方案
#1
4
Yes you can do this in a vectorized form:
是的,您可以以矢量化形式执行此操作:
p,m,n,r = a.shape
a.reshape(-1,r)[np.arange(p*m*n),b.ravel()] = 1
This should generalize more easily to higher order ndarrays.
这应该更容易推广到更高阶的ndarray。
#1
4
Yes you can do this in a vectorized form:
是的,您可以以矢量化形式执行此操作:
p,m,n,r = a.shape
a.reshape(-1,r)[np.arange(p*m*n),b.ravel()] = 1
This should generalize more easily to higher order ndarrays.
这应该更容易推广到更高阶的ndarray。