2014-01-07 129 views
1

我有一個2D numpy的陣列,例如作爲:索引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 

然後我想選擇對應於該匹配的標準,例如所有的數值a1 [切片索引: ,1]包含在範圍(l1,l2)中:

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)) 

在工作(它給unhashable類型: 'numpy.ndarray')

我的想法是,然後使用這些索引來映射大小的另一個陣列(500,N)。

是否有任何合理的方式來選擇這樣的索引?或者:在這種情況下是否需要使用一些遮罩?

回答

3

這應該工作

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

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

感謝:它確實有效! – gluuke

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 

事後你可以不只是從你的新陣列選擇你做,你需要(假設你的新陣列的尺寸爲(500,N))的點,做

print newarray[c,:] 
+0

不錯的解決方案太:)而且它的工作原理 – gluuke

+1

最好使用np.logical_and(),而不是乘法。 Afaik會在所有相關情況下給出相同的結果和相同的性能,但它會使代碼的結構更加明確。 –

+0

@EelcoHoogendoorn不完全確定你的意思是「更明確」,但對我來說,乘法更具可讀性,儘管這可能是由於我的數學背景,對於程序員來說,「np.logical_and」更具可讀性。 – usethedeathstar