Jak uzyskać indeks maksymalnego elementu w tablicy NumPy wzdłuż jednej osi

Mam dwuwymiarową tablicę NumPy. Wiem jak uzyskać maksymalne wartości nad osiami:

>>> a = array([[1,2,3],[4,3,1]])
>>> amax(a,axis=0)
array([4, 3, 3])

Jak mogę uzyskać indeksy maksymalnych elementów? Chciałbym zamiast tego jako wyjście array([1,1,0]).

Author: Trilarion, 2011-03-29

5 answers

>>> a.argmax(axis=0)

array([1, 1, 0])
 155
Author: eumiro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-29 07:39:43
>>> import numpy as np
>>> a = np.array([[1,2,3],[4,3,1]])
>>> i,j = np.unravel_index(a.argmax(), a.shape)
>>> a[i,j]
4
 104
Author: blaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-23 20:52:54

argmax() zwróci tylko pierwsze wystąpienie dla każdego wiersza. http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html

Jeśli kiedykolwiek trzeba to zrobić dla tablicy w kształcie, to działa lepiej niż unravel:

import numpy as np
a = np.array([[1,2,3], [4,3,1]])  # Can be of any shape
indices = np.where(a == a.max())
Możesz również zmienić swoje warunki:
indices = np.where(a >= 1.5)

Powyższe daje wyniki w postaci, o którą prosiłeś. Alternatywnie, można przekonwertować na listę współrzędnych x, y przez:

x_y_coords =  zip(indices[0], indices[1])
 36
Author: SevakPrime,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-04 21:20:18
v = alli.max()
index = alli.argmax()
x, y = index/8, index%8
 2
Author: ahmed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-10 04:27:19

Istnieje argmin() i argmax() dostarczone przez numpy, które zwracają indeks min i max tablicy numpy.

Powiedz np. dla tablicy 1-D zrobisz coś takiego

import numpy as np

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

print(a.argmax()) # returns 0
print(a.argmin()) # returns 2

I podobnie dla tablicy wielowymiarowej

import numpy as np

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

print(a.argmax()) # returns 4
print(a.argmin()) # returns 0

Zauważ, że zwrócą one tylko indeks pierwszego wystąpienia.

 2
Author: Hadi Mir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-08 16:47:35