2015-10-14 100 views
0

Numpy是否具有快速搜索二维数组中的元素并返回其索引的功能? 平均例如:numpy数组中的Python快速搜索

a=54 
array([[ 0, 1, 2, 3], 
     [ 4, 5, 54, 7], 
     [ 8, 9, 10, 11]]) 

所以等于值将是array[1][2]。 我当然可以用简单的loops-,但我想类似的东西:

if 54 in arr 
+0

是否有更多的代码? –

+1

'numpy.where(a == 54)'可能是你正在寻找的 – Akavall

+0

[是否有Numpy函数返回数组中某个东西的第一个索引?](http://stackoverflow.com/问题/ 432112/is-n-numpy-function-to-return-first-index-of-an-an-an-an-an-array) – paisanco

回答

2
In [4]: import numpy as np 

In [5]: my_array = np.array([[ 0, 1, 2, 3], 
          [ 4, 5, 54, 7], 
          [8, 54, 10, 54]]) 

In [6]: my_array 
Out[6]: 
array([[ 0, 1, 2, 3], 
     [ 4, 5, 54, 7], 
     [ 8, 54, 10, 54]]) 

In [7]: np.where(my_array == 54) #indices of all elements equal to 54 
Out[7]: (array([1, 2, 2]), array([2, 1, 3])) #(row_indices, col_indices) 

In [10]: temp = np.where(my_array == 54) 

In [11]: zip(temp[0], temp[1]) # maybe this format is what you want 
Out[11]: [(1, 2), (2, 1), (2, 3)] 
+0

是你的变体正是我需要的,它返回元素的索引,但我使用的数组被命名为具有混合值的数组。 new_array = np.core.records.fromrecords([(data [0],data [1],data [2],data [3],data [4],data [5],NDate)],names ='Date ,Name,Age,Start,End,Avg,NDate',formats ='S10,f8,f8,f8,f8,f8,f16')。并且当我使用temp = np.where(new_array == 7.43)时,它会返回我“”(array([],dtype = int32)),但不是值的索引。但是数组中存在7.43的值。 – Riggun