python在NumPy数组中查找等于零的元素索引

numpy.where()是我的最爱。

>>> import numpy 
>>> x = numpy.array([1, 0, 2, 0, 3, 0, 4, 5, 6, 7, 8])
>>> numpy.where(x == 0)[0]
array([1, 3, 5])
>>> numpy.where(x == 0)
Out[14]: array([1, 3, 5], dtype=int64)

您可以搜索任何标量条件:

import numpy as np
a = np.asarray([0, 1, 2, 3, 4])
a == 0  # or whatever

Out[15]: array([ True, False, False, False, False])

有np.argwhere,

import numpy as np
arr = np.array([[1, 2, 3], [0, 1, 0], [7, 0, 2]])

arr
Out[18]: 
array([[1, 2, 3],
       [0, 1, 0],
       [7, 0, 2]])

它将所有找到的索引作为行返回:

np.argwhere(arr == 0)
Out[16]: 
array([[1, 0],  # Indices of the first zero
       [1, 2],  # Indices of the second zero
       [2, 1]],   # Indices of the third zero
       dtype=int64)

也可以在条件的布尔掩码上使用它来使用nonzero(),因为mtrw也是一种零。

import numpy as np

x = np.array([1, 0, 2, 0, 3, 0, 4, 5, 6, 7, 8])

x == 0
Out[20]: 
array([False,  True, False,  True, False,  True, False, False, False,
       False, False])

np.nonzero(x == 0)[0]
Out[21]: array([1, 3, 5], dtype=int64)

如果你正在使用一维数组,那么就有一个语法糖:

import numpy as np

x = np.array([1, 0, 2, 0, 3, 0, 4, 5, 6, 7, 8])

np.flatnonzero(x == 0)
Out[24]: array([1, 3, 5], dtype=int64)
import numpy as np

x = np.array([1, 0, 2, 3, 6])
non_zero_arr = np.extract(x > 0, x)

non_zero_arr
Out[28]: array([1, 2, 3, 6])

min_index = np.amin(non_zero_arr)
min_index
Out[26]: 1

min_value = np.argmin(non_zero_arr)
min_value
Out[27]: 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值