【问题标题】:indexing numpy array with logical operator用逻辑运算符索引 numpy 数组
【发布时间】:2014-01-25 07:31:12
【问题描述】:

我有一个 2d numpy 数组,例如:

import numpy as np
a1 = np.zeros( (500,2) )

a1[:,0]=np.arange(0,500)
a1[:,1]=np.arange(0.5,1000,2)
# could be also read from txt

然后我想选择与一个条件匹配的切片对应的索引,例如范围 (l1,l2) 中包含的所有值 a1[:,1]:

l1=20.0; l2=900.0; #as example

我想用简洁的表达方式。但是,两者都不是:

np.where(a1[:,1]>l1 and a1[:,1]<l2)

(它给出 ValueError 并建议使用 np.all,在这种情况下我不清楚);两者都没有:

np.intersect1d(np.where(a1[:,1]>l1),np.where(a1[:,1]<l2))

正在工作(它提供不可散列的类型:'numpy.ndarray')

然后我的想法是使用这些索引来映射另一个大小为 (500,n) 的数组。

有没有合理的方式来选择索引?或者:在这种情况下是否需要使用一些掩码?

【问题讨论】:

    标签: python arrays numpy indexing


    【解决方案1】:

    这应该可以工作

    np.where((a1[:,1]>l1) & (a1[:,1]<l2))
    

    np.where(np.logical_and(a1[:,1]>l1, a1[:,1]<l2))
    

    【讨论】:

      【解决方案2】:

      这是你想要的吗?

      import numpy as np
      a1 = np.zeros( (500,2) )
      a1[:,0]=np.arange(0,500)
      a1[:,1]=np.arange(0.5,1000,2)
      c=(a1[:,1]>l1)*(a1[:,1]<l2) # boolean array, true if the item at that position is ok according to the criteria stated, false otherwise 
      print a1[c] # prints all the points in a1 that correspond to the criteria 
      

      之后,您不仅可以从您制作的新数组中选择您需要的点(假设您的新数组具有维度 (500,n)),还可以通过

      print newarray[c,:]
      

      【讨论】:

      • 最好使用 np.logical_and(),而不是乘法。 Afaik 他们将在所有相关情况下给出相同的结果和相同的性能,但它使代码的结构更加明确。
      • @EelcoHoogendoorn 不完全确定您所说的“更明确”是什么意思,但对我来说,乘法更具可读性,尽管这可能是由于我的数学背景,而对于程序员来说,“np.logical_and " 更具可读性?
      • 我也有数学背景;从这个角度来看,> 运算符的类型是布尔型,因此使用逻辑运算符是有意义的。在大多数语言或形式系统中,布尔乘法甚至没有定义为运算符。从 CS 的角度来看;乘法发生的事情是从 bool 到 int 的隐式转换。 Python 之禅让我们相信显式 > 隐式。我是信徒,但你的里程可能会有所不同;)
      猜你喜欢
      • 2012-08-27
      • 2014-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-20
      相关资源
      最近更新 更多