[英]Replace first occurence of 0 in a 2D numpy array
I have a 2D array:我有一个二维数组:
[[1,2,0,0],
[4,0,9,4],
[0,0,1,0],
[4,6,9,0]]
is there an efficient way (without using loops) to replace every first 0 in the array, with a 1:是否有一种有效的方法(不使用循环)将数组中的每个第一个 0 替换为 1:
[[1,2,1,0],
[4,1,9,4],
[1,0,1,0],
[4,6,9,1]]
? ?
Thanks a lot !非常感谢 !
So, you can use np.where
to get the indices of the rows and columns where the array is 0:因此,您可以使用np.where
获取数组为 0 的行和列的索引:
In [45]: arr = np.array(
...: [[1,2,0,0],
...: [4,0,9,4],
...: [0,0,1,0],
...: [4,6,9,0]]
...: )
In [46]: r, c = np.where(arr == 0)
Then, use np.unique
to get the unique x values, which will correspond to the first incidence of 0
in each row, and use return_index
to get the indices to extract the corresponding column values:然后,使用np.unique
获取唯一的 x 值,这将对应于每行中第一次出现的0
,并使用return_index
获取索引以提取相应的列值:
In [47]: uniq_val, uniq_idx = np.unique(r, return_index=True)
In [48]: arr[uniq_val, c[uniq_idx]] = 1
In [49]: arr
Out[49]:
array([[1, 2, 1, 0],
[4, 1, 9, 4],
[1, 0, 1, 0],
[4, 6, 9, 1]])
If performance is really an issue, you could just write a numba
function, I suspect this would be very amenable to numba
如果性能真的是一个问题,你可以写一个numba
function,我怀疑这对numba
来说是非常适合的
Here is a one-liner inspired by the accepted answer of this question :这是一个受这个问题的公认答案启发的单行代码:
a = np.array([
[1, 2, 0, 0],
[4, 0, 9, 4],
[0, 0, 1, 0],
[4, 6, 9, 0]
])
a[range(len(a)), np.argmax(a == 0, axis=1)] = 1
Im not sure if this is that efficent, but its better than loops at least.我不确定这是否有效,但至少比循环好。 We search for the first 0 in each row, then extend this to coordinates and set those to 1.我们搜索每行中的第一个 0,然后将其扩展到坐标并将其设置为 1。
filter = np.argmax(a == 0, axis=1)
f = np.column_stack((np.array(range(4)),filter))
a[[*f.T]] = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.