【问题标题】:How do I return a nonflat numpy array selecting elements given a set of conditions?如何在给定一组条件的情况下返回非平面 numpy 数组选择元素?
【发布时间】:2017-03-01 14:12:00
【问题描述】:

我有一个多维数组,比如形状 (4, 3),看起来像

a = np.array([(1,2,3),(4,5,6),(7,8,9),(10,11,12)])

如果我有一个固定条件列表

conditions = [True, False, False, True]

如何返回列表

array([(1,2,3),(10,11,12)])

使用np.extract 返回

>>> np.extract(conditions, a)
array([1, 4])

它只返回每个嵌套数组的第一个元素,而不是数组本身。我不确定是否或如何使用np.where 做到这一点。非常感谢任何帮助,谢谢!

【问题讨论】:

    标签: python arrays numpy conditional slice


    【解决方案1】:

    让我们定义你的变量:

    >>> import numpy as np
    >>> a = np.array([(1,2,3),(4,5,6),(7,8,9),(10,11,12)])
    >>> conditions = [True, False, False, True]
    

    现在,让我们选择您想要的元素:

    >>> a[np.array(conditions)]
    array([[ 1,  2,  3],
           [10, 11, 12]])
    

    一边

    请注意,更简单的a[conditions] 有一些歧义:

    >>> a[conditions]
    -c:1: FutureWarning: in the future, boolean array-likes will be handled as a boolean array index
    array([[4, 5, 6],
           [1, 2, 3],
           [1, 2, 3],
           [4, 5, 6]])
    

    如您所见,conditions 在这里被视为(类整数)索引值,这不是我们想要的。

    【讨论】:

      【解决方案2】:

      您可以使用简单的列表切片和np.where 它或多或少是专门针对这种情况设计的..

      >>> a[np.where(conditions)]
      array([[[ 1,  2,  3],
              [10, 11, 12]]])
      

      【讨论】:

      • 在对大型数组进行快速测试时,令人惊讶的是它比转换为数组和布尔索引要快一些!
      猜你喜欢
      • 2011-03-03
      • 2012-03-17
      • 2019-12-15
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多