Python 使用逻辑运算符索引numpy数组

Python 使用逻辑运算符索引numpy数组,python,arrays,numpy,indexing,Python,Arrays,Numpy,Indexing,我有一个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])的切片对应的索引: 我想用一个简明的表达。然而,这两种情况都不是: np.where(a1[:,1]>l1 and a

我有一个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])的切片对应的索引:

我想用一个简明的表达。然而,这两种情况都不是:

np.where(a1[:,1]>l1 and a1[:,1]<l2)
np.where(a1[:,1]>l1和a1[:,1]l1),np.where(a1[:,1]这应该有效

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

np.where((a1[:,1]>l1)和(a1[:,1]l1,a1[:,1]这是你想要的吗

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 

最好使用np.logical_和(),而不是乘法。这样,在所有相关情况下,它们将给出相同的结果和相同的性能,但这会使代码的结构更加明确。@EELCoogendoorn不完全确定“更明确”是什么意思,但对我来说乘法更具可读性,尽管这可能是因为我的数学背景,而对于程序员来说,乘法是“np.logical_和”更具可读性?我也有数学背景;从这个角度来看,>运算符的类型是bool,因此使用逻辑运算符是有意义的。在大多数语言或形式系统中,bools的乘法甚至没有定义为运算符。从CS的角度来看,乘法的作用是从bool隐式转换为intPython的禅宗会让我们相信显式>隐式。我相信,但你的里程可能会有所不同;)
np.where((a1[:,1]>l1) & (a1[:,1]<l2))
np.where(np.logical_and(a1[:,1]>l1, a1[:,1]<l2))
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 
print newarray[c,:]