numpy array , TypeError: cannot unpack non-iterable numpy.int64 object

numpy array , TypeError: cannot unpack non-iterable numpy.int64 object

我要在 2D numpy ndarray 中找到每列的最大值及其索引,但出现错误

TypeError: cannot unpack non-iterable numpy.int64 object

这是我的代码

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 

有人知道吗?

np.argmax 正如你所拥有的那样,它正在展平数组并返回一个标量,因此你的解包错误。

尝试:

ncols = a.shape[1]
idx = np.argmax(a, axis=0)
vals = a[idx, np.arange(ncols)]

输出:

>>> idx
array([6, 3, 2, 0, 1, 0, 2])

>>> vals
array([ 4,  6,  8,  5,  9, 12, 13])

你需要这个:

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