2017-01-02 109 views
1

如何查找3D數組中最大值的座標如果我想查找它們的全部座標?在Numpy數組中如何查找值的所有座標

這是我的代碼到目前爲止,但它不工作,我不明白爲什麼。

s = set() 
elements = np.isnan(table) 
numbers = table[~elements] 
biggest = float(np.amax(numbers)) 
a = table.tolist() 
for x in a: 
    coordnates = np.argwhere(table == x) 
    if x == biggest: 
     s.add((tuple(coordinates[0])) 
print(s) 

例如:

table = np.array([[[ 1, 2, 3], 
     [ 8, 4, 11]], 

     [[ 1, 4, 4], 
     [ 8, 5, 9]], 

     [[ 3, 8, 6], 
     [ 11, 9, 8]], 

     [[ 3, 7, 6], 
     [ 9, 3, 7]]]) 

應該返回s = {(0, 1, 2),(2, 1, 0)}

+0

有沒有理由不使用Numpy? –

+0

我試過使用Numpy,我只是沒有找到一個能夠返回所有座標的特定函數,是不是有一個? – Jana

+1

'np.argwhere(table == table.max())'''array([[0,1,2],[2,1,0]])''。 –

回答

0

結合np.argwherenp.max(如在評論中已經指出@AshwiniChaudhary)可以被用來尋找座標:

>>> np.argwhere(table == np.max(table)) 
array([[0, 1, 2], 
     [2, 1, 0]], dtype=int64) 

To g等的一組時,可以使用一組-理解(一個需要的子陣列轉化爲元組,從而可以將它們存儲在該組):

>>> {tuple(coords) for coords in np.argwhere(table == np.max(table))} 
{(0, 1, 2), (2, 1, 0)} 
0
In [193]: np.max(table) 
Out[193]: 11 
In [194]: table==np.max(table) 
Out[194]: 
array([[[False, False, False], 
     [False, False, True]], 
    ... 
     [[False, False, False], 
     [False, False, False]]], dtype=bool) 
In [195]: np.where(table==np.max(table)) 
Out[195]: 
(array([0, 2], dtype=int32), 
array([1, 1], dtype=int32), 
array([2, 0], dtype=int32)) 

transpose匝3個陣列的這個元組成陣列2套座標:

In [197]: np.transpose(np.where(table==np.max(table))) 
Out[197]: 
array([[0, 1, 2], 
     [2, 1, 0]], dtype=int32) 

這種操作是很常見,它已被包裹在一個函數調用(看一下它的文檔)

In [199]: np.argwhere(table==np.max(table)) 
Out[199]: 
array([[0, 1, 2], 
     [2, 1, 0]], dtype=int32) 
相關問題