2

I have the following example of an array with grades:

grades = np.array([[ 1,  1,  2,  -3],[ 4,  5,  6,  7],[ 8,  9, -3, 11],[12, 13, 14, 15]])

I would like to identify the elements with "-3" and change their entire row to that number, for example the result:

grades = np.array([[ -3,  -3,  -3,  -3],[ 4,  5,  6,  7],[ -3,  -3, -3, -3],[12, 13, 14, 15]])

So far I tried:

grades[np.argwhere(grades==-3)]=-3

but i get the following result, where the there are other rows affected as well:

array([[-3, -3, -3, -3],[ 4,  5,  6,  7],[-3, -3, -3, -3],[-3, -3, -3, -3],[16, 17, 18, 19]])

Any Idea please? Thanks!

1 Answer 1

5

First find which of the rows contain a -3 using simple == and numpy.any. Now index on this boolean array and assign -3 to it, broadcasting will take care of the rest.

>>> grades = np.array([[ 1,  1,  2,  -3],[ 4,  5,  6,  7],[ 8,  9, -3, 11],[12, 13, 14, 15]])
>>> grades[np.any(grades == -3, axis=1)] = -3
>>> grades
array([[-3, -3, -3, -3],
       [ 4,  5,  6,  7],
       [-3, -3, -3, -3],
       [12, 13, 14, 15]])
Sign up to request clarification or add additional context in comments.

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.