Reputation: 67
I'm going to find the max value of each column and its index in a 2D numpy ndarray
but I got the error
TypeError: cannot unpack non-iterable numpy.int64 object
here is my code
import numpy as np
a = np.array([[1,0,4,5,8,12,8],
[1,3,0,4,9,1,0],
[1,5,8,5,9,7,13],
[1,6,2,2,9,5,0],
[3,5,5,5,9,4,13],
[1,5,4,5,9,4,13],
[4,5,4,4,9,7,4]
])
x,y = np.argmax(a)
#x should be max of each column and y the index of it
does anybody know about it?
Upvotes: 2
Views: 5463
Reputation: 4049
np.argmax
as you have it is flattening the array and returning a scalar, hence your unpacking error.
Try:
ncols = a.shape[1]
idx = np.argmax(a, axis=0)
vals = a[idx, np.arange(ncols)]
Output:
>>> idx
array([6, 3, 2, 0, 1, 0, 2])
>>> vals
array([ 4, 6, 8, 5, 9, 12, 13])
Upvotes: 3