【问题标题】:Find indices of the elements smaller than x in a numpy array在 numpy 数组中查找小于 x 的元素的索引
【发布时间】:2017-05-09 14:53:04
【问题描述】:

假设我有一个 numpy 数组,例如:

import numpy as np    
arr = np.array([10,1,2,5,6,2,3,8])

如何提取包含小于 6 的元素索引的数组,得到以下结果:

np.array([1,2,3,5,6])

我想要一些行为类似于 np.nonzero() 但不是测试非零值,而是测试小于 x 的值

【问题讨论】:

  • 应该对元素进行排序吗?或者这只是一个“可能的”结果?
  • "but instead of testing for nonzero value, it test for value smaller than x"。那么,测试一下?你已经提到了np.nonzero
  • 以@Divakar 的提示为基础,False 的值计算为零
  • 是的,看了 Psidom 的回答,我觉得有点傻。

标签: python numpy


【解决方案1】:

您可以在布尔掩码上使用numpy.flatnonzero,并在 a 的扁平化版本中返回非零索引

np.flatnonzero(arr < 6)
# array([1, 2, 3, 5, 6])

一维数组的另一个选项是numpy.where

np.where(arr < 6)[0]
# array([1, 2, 3, 5, 6])

【讨论】:

    【解决方案2】:

    最简单的方法是通过

    arr[arr<6]
    

    【讨论】:

    • 这将给出 而不是索引
    【解决方案3】:

    我会建议一种更简洁且易于解释的方法: 首先,找到条件有效的索引:

    >> indices = arr < 6
    >> indices
    >> [False, True, True, True, False, True, False]
    

    然后,使用索引进行索引:

    >> arr[indices]
    >> [1, 2, 5, 2, 3]
    

    或在原始数组中找到正确的位置:

    >> np.where(indices)[0]
    >> [1, 2, 3, 5, 6]
    

    【讨论】:

      猜你喜欢
      • 2011-06-03
      • 2019-07-12
      • 1970-01-01
      • 2012-11-22
      • 2017-12-01
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多