2016-08-25 28 views
0

我有號碼的具有形狀的陣列(1220)檢索某些indicies稱爲x的Python - 從陣列

我看數字大於1.0,

mask1 = [i for i in x if i>1.0 ] 

返回

[1.2958354, 1.0839227, 1.1919032] 

我現在的問題是如何能夠確定這些值的索引位置在我的初始數組x

我已經試過單獨每次,但出現錯誤

list(x).index(1.2958354) 

ValueError: 1.2958354 is not in list 

回答

1

可以使用枚舉函數,例如:

mask1 = [(i, value) for i, value in enumerate(x) if value>1.0 ] 
print mask1 
1

嘗試:

mask1 = [i for i in range(len(x)) if x[i]>1.0] 
1

可以使用index功能上x,這將返回每個值的第一指標。從mask1嘗試讓所有的指數列表:

map(x.index, mask1) 
1

mask_1 = [index for index, value in enumerate(x) if value > 1.0]

1

嘗試使用enumerate()獲得指數和價值在一起:

mask1 = [(i,v) for i,v in enumerate(x) if v > 1.0] 
1

使用枚舉來創建tu這些索引和過濾值對,然後使用帶*操作符的zip將變量解壓到單獨的列表中。

a = np.array([0, 1, 2, 3]) 

idx, vals = zip(*[(i, v) for i, v in enumerate(a) if v > 1]) 

>>> idx 
(2, 3) 

>>> vals 
(2, 3) 
4

您已經標記了這個作爲numpy,並描述shape(不len)。這導致我認爲你有一個numpy數組。

In [665]: x=np.random.rand(10) 
In [666]: x 
Out[666]: 
array([ 0.6708692 , 0.2856505 , 0.19186508, 0.59411697, 0.1188686 , 
     0.54921919, 0.77402055, 0.12569494, 0.08807101, 0.11623299]) 
In [667]: x>.5 
Out[667]: array([ True, False, False, True, False, True, True, False, False, False], dtype=bool) 
In [668]: list(x).index(.6708692) 
ValueError: 0.6708692 is not in list 

的原因ValueError是,你正在尋找一個浮動,而那些經常不完全匹配。如果數組是整數,那麼這樣的索引就可以工作。

In [669]: list(np.arange(10)).index(5) 
Out[669]: 5 

此推理適用x是否是一個數組或列表。

numpy具有where返回布爾真值的指數中的陣列

In [670]: np.where(x>.5) 
Out[670]: (array([0, 3, 5, 6], dtype=int32),) 

x>.5是如上所示的布爾數組,和[0,3,5,6]索引值,其中這是真的。

In [671]: x[np.where(x>.5)] 
Out[671]: array([ 0.6708692 , 0.59411697, 0.54921919, 0.77402055]) 

的平等測試不起作用任何更好

In [672]: x[np.where(x==0.6708692)] 
Out[672]: array([], dtype=float64) 

對於花車有一種close概念 - 不同的是一定誤差內(np.allclose是特別有用):

In [679]: np.where(np.isclose(x,0.59411697)) 
Out[679]: (array([3], dtype=int32),) 

對於列表,枚舉解決方案之一是偉大的,也適用於1D數組。但它已經是一個陣列,使用where