更新时间:2023-08-28 23:21:04
使用 np.argmax
沿非零掩码上的该轴(此处为列的零轴)获取第一个matches
(真实值)的索引-
Use np.argmax
along that axis (zeroth axis for columns here) on the mask of non-zeros to get the indices of first matches
(True values) -
(arr!=0).argmax(axis=0)
扩展到涵盖通用轴说明符,并且在沿着该轴找不到元素的非零的情况下,我们将有一个类似这样的实现-
Extending to cover generic axis specifier and for cases where no non-zeros are found along that axis for an element, we would have an implementation like so -
def first_nonzero(arr, axis, invalid_val=-1):
mask = arr!=0
return np.where(mask.any(axis=axis), mask.argmax(axis=axis), invalid_val)
请注意,由于所有False
值上的argmax()
返回0
,因此如果所需的invalid_val
是0
,我们将直接使用mask.argmax(axis=axis)
获得最终输出.
Note that since argmax()
on all False
values returns 0
, so if the invalid_val
needed is 0
, we would have the final output directly with mask.argmax(axis=axis)
.
样品运行-
In [296]: arr # Different from given sample for variety
Out[296]:
array([[1, 0, 0],
[1, 1, 0],
[0, 1, 0],
[0, 0, 0]])
In [297]: first_nonzero(arr, axis=0, invalid_val=-1)
Out[297]: array([ 0, 1, -1])
In [298]: first_nonzero(arr, axis=1, invalid_val=-1)
Out[298]: array([ 0, 0, 1, -1])
扩展到涵盖所有比较操作
要找到第一个zeros
,只需在函数中使用arr==0
作为mask
.对于等于某个特定值val
的第一个,对于所有arr == val,依此类推. "noreferrer> comparisons
可能在这里.
To find the first zeros
, simply use arr==0
as mask
for use in the function. For first ones equal to a certain value val
, use arr == val
and so on for all cases of comparisons
possible here.
要查找符合特定比较条件的最后一个,我们需要沿该轴翻转并使用与argmax
相同的想法,然后通过偏离轴长来补偿翻转,如下所示-
To find the last ones matching a certain comparison criteria, we need to flip along that axis and use the same idea of using argmax
and then compensate for the flipping by offsetting from the axis length, as shown below -
def last_nonzero(arr, axis, invalid_val=-1):
mask = arr!=0
val = arr.shape[axis] - np.flip(mask, axis=axis).argmax(axis=axis) - 1
return np.where(mask.any(axis=axis), val, invalid_val)
样品运行-
In [320]: arr
Out[320]:
array([[1, 0, 0],
[1, 1, 0],
[0, 1, 0],
[0, 0, 0]])
In [321]: last_nonzero(arr, axis=0, invalid_val=-1)
Out[321]: array([ 1, 2, -1])
In [322]: last_nonzero(arr, axis=1, invalid_val=-1)
Out[322]: array([ 0, 1, 1, -1])
同样,此处涵盖了所有 comparisons
的情况通过使用相应的比较器获取mask
,然后在列出的函数中使用.
Again, all cases of comparisons
possible here are covered by using the corresponding comparator to get mask
and then using within the listed function.