1

I have an array like so, reshaped it, and need to replace the max value in each row (so axis=1?) with 0. I can't use for loops.

x = np.random.uniform(1.0, 21.0, 20)
print("Original array: ", x)

xMatrix = x.reshape(4, 5)
print(xMatrix)

maxNum = np.amax(xMatrix, axis=1)

So, maxNum only gives me the max value in each row, obviously. But how would I go about actually replacing those values without simply looping through the array?

4 Answers 4

1

Try np.where combined with np.isin :

np.where(np.isin(xMatrix,maxNum), 0, xMatrix)
Sign up to request clarification or add additional context in comments.

Comments

1

Following is a way to do this in a single pass, unlike other answers here that first find the max and then search for it.

This solution finds the INDEX of the max value in each row, then assigns 0 to that index.

import numpy as np

x = np.random.uniform(1.0, 21.0, 20)
print("Original array: ", x)

xMatrix = x.reshape(4, 5)
print(xMatrix)

gives

xMatrix
Out[28]: 
array([[10.10437809,  6.4552141 , 15.1040498 ,  1.94380305, 15.27380855],
       [12.08934681, 19.20744506, 14.12271304,  8.45470779,  6.2887767 ],
       [ 7.74326665, 14.63460522, 12.07651464, 15.80510958,  2.24595519],
       [16.12620326, 16.29083185,  7.96133555, 10.61357712, 14.6664017 ]])

then

max_ind = np.argmax(xMatrix, axis=1)
row_ind = np.arange(xMatrix.shape[0])
multi_ind = np.array([row_ind, max_ind])
linear_ind = np.ravel_multi_index(multi_ind, xMatrix.shape)
xMatrix.reshape((-1))[linear_ind] = 0
xMatrix
Out[37]: 
array([[10.10437809,  6.4552141 , 15.1040498 ,  1.94380305,  0.        ],
       [12.08934681,  0.        , 14.12271304,  8.45470779,  6.2887767 ],
       [ 7.74326665, 14.63460522, 12.07651464,  0.        ,  2.24595519],
       [16.12620326,  0.        ,  7.96133555, 10.61357712, 14.6664017 ]])

Comments

0

You can use map and lamda function like this

list(map(lambda x : max(x), xMatrix))

Comments

0

I got it what you are looking for Use simple comparison operators and its done

xMatrix[xMatrix == max_num[:, None]] = 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.