Get maximum subset in multidimensional array

Viewed 106

Given:

a=np.array([[-0.00365169, -1.96455717,  1.44163783,  0.52460176,  2.21493637], 
            [-1.05303533, -0.7106505,   0.47988974,  0.73436447, -0.87708389],
            [-0.76841759,  0.8405524,   0.91184575, -0.70652033,  0.37646991]])

I would like to get the maximum subset (in this case, the first row):

[-0.00365169, -1.96455717,  1.44163783,  0.52460176,  2.21493637]

By using print(np.amax(a, axis=0)), I'm getting the wrong result:

[-0.00365169  0.8405524   1.44163783  0.73436447  2.21493637]

How can we get the correct maximum subset?

2 Answers

You can sum along columns and then find the index with the maximum value with argmax:

a[np.argmax(a.sum(axis=1))]

If you make some change:

a=np.array([[-0.00365169, -10.96455717,  1.44163783,  0.52460176,  2.21493637], 
            [-1.05303533, -0.7106505,   0.47988974,  0.73436447, -0.87708389],
            [-0.76841759,  0.8405524,   0.91184575, -0.70652033,  0.37646991]])

The solution will be not right:

a[np.argmax(a.sum(axis=1))]

Try this:

arr = np.where(a == np.amax(a, axis=0))[0]
counts = np.unique(arr)
ind = np.argmax(counts)
print(a[arr[ind]])
Related