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,
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)