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

时间:2011-01-03 21:40:09

标签: python numpy

NumPy具有高效的函数/方法nonzero()来识别ndarray对象中非零元素的索引。获取的元素索引的最有效方法是什么?

8 个答案:

答案 0 :(得分:179)

numpy.where()是我最喜欢的。

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

答案 1 :(得分:23)

np.argwhere

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

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

array([[1, 0],    # Indices of the first zero
       [1, 2],    # Indices of the second zero
       [2, 1]],   # Indices of the third zero
      dtype=int64)

答案 2 :(得分:22)

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

>>> a = np.asarray([0,1,2,3,4])
>>> a == 0 # or whatver
array([ True, False, False, False, False], dtype=bool)

将数组作为条件的布尔掩码返回。

答案 3 :(得分:12)

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

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

>>> x==0
array([False, True, False, True, False, True, False, False, False, False, False], dtype=bool)

>>> numpy.nonzero(x==0)[0]
array([1, 3, 5])

它与mtrw的方式完全相同,但它与问题更相关;)

答案 4 :(得分:4)

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

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

答案 5 :(得分:1)

import numpy as np

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

min_index = np.amin(non_zero_arr)
min_value = np.argmin(non_zero_arr)

答案 6 :(得分:1)

我会按以下方式进行:

>>> x = np.array([[1,0,0], [0,2,0], [1,1,0]])
>>> x
array([[1, 0, 0],
       [0, 2, 0],
       [1, 1, 0]])
>>> np.nonzero(x)
(array([0, 1, 2, 2]), array([0, 1, 0, 1]))

# if you want it in coordinates
>>> x[np.nonzero(x)]
array([1, 2, 1, 1])
>>> np.transpose(np.nonzero(x))
array([[0, 0],
       [1, 1],
       [2, 0],
       [2, 1])

答案 7 :(得分:1)

您可以使用numpy.nonzero查找零。

  public static String getPrettyPrintVal(double input){
    final DecimalFormat decimalFormat = new DecimalFormat("###,###.###", DecimalFormatSymbols.getInstance(Locale.GERMANY));
    return decimalFormat.format(input);
}