2

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?

2 Answers 2

3

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])
Sign up to request clarification or add additional context in comments.

Comments

2

You need this:

x = a.max(0)
y = a.argmax(0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.