[英]indexing numpy array with logical operator
我有一個二維的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)的數組。
有任何合理的方式選擇索引嗎? 或者:在這種情況下是否需要使用口罩?
這應該工作
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
之后,您不僅可以從制作的新數組中選擇所需的點(假設新數組的尺寸為(500,n)),還可以
print newarray[c,:]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.