Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Substitue row in Numpy if a condition is met

I have a matrix in NumPy as:

[[10 10]
 [11 10]
 [12 10]
 [13 10]
 [14 10]]

My goal is to replace a row if a particular condition on the left element is met.

For example,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have values: z= 13, x=1, y=0. I’d like something as:

If one of the left elements is equal to z then replace the row with [x y]

So far I wrote something like this:

values = np.array([[10 10]
     [11 10]
     [12 10]
     [13 10]
     [14 10]])
z = 13
x = 1
y = 0
values = np.where(values == [z, ], np.array([x, y]), values)

The code works well for replacing the left element (x is updated), but y for some reason stays the same or gets the value of another row somehow.

Does anyone know what could I do? Or if there is another method whatsoever?

>Solution :

Try values[values[:, 0] == z] = [x, y] — i.e., rows whose 1st entry is z are set to [x, y].

import numpy as np

values = np.array([[10, 10],
     [11, 10],
     [12, 10],
     [13, 10],
     [14, 10]])
z = 13
x = 1
y = 0

values[values[:, 0] == z] = [x, y]

print(values)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading