1

If I have a NumPy array and a list of row indices:

import numpy as np

x = np.random.rand(50).reshape(10,5)
row_idx = [0, 1, 4]

How do I set all of the values in the rows in row_idx that are less that 0.5 to zero?

I've tried:

x[row_idx][x[row_idx] < 0.5] = 0.0

But this didn't do anything

1 Answer 1

1

You can do it with np.where:

In [26]: x[row_idx] = np.where(x[row_idx] < 0.5, 0, x[row_idx])

In [27]: x
Out[27]:
array([[0.94870486, 0.        , 0.        , 0.89030411, 0.50505295],
       [0.56803186, 0.90804518, 0.69843535, 0.77174293, 0.        ],
       [0.1318847 , 0.95940137, 0.92036048, 0.669007  , 0.15404623],
       [0.90021311, 0.72959638, 0.82705006, 0.65329554, 0.3714969 ],
       [0.56293165, 0.        , 0.        , 0.        , 0.        ],
       [0.46015752, 0.96294812, 0.0678065 , 0.66693152, 0.69825679],
       [0.63310433, 0.59532105, 0.75913618, 0.60258213, 0.48668606],
       [0.69935925, 0.15807776, 0.8589115 , 0.37657828, 0.69651669],
       [0.87587399, 0.68772743, 0.59854082, 0.67857679, 0.34182774],
       [0.3734155 , 0.06255165, 0.02622334, 0.17993743, 0.1783275 ]])
Sign up to request clarification or add additional context in comments.

2 Comments

Any explanation as to why OP's code doesn't work when both x[row_idx] = 0.0 and x[x < 0.5] = 0.0 do work?
His second indexing turns it into a 1D array, which you can see if you exclude the assignment.

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.