Home > Blockchain >  Substitute row in Numpy if a condition is met
Substitute row in Numpy if a condition is met

Time:11-10

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 like:

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

So far I wrote something like this:

import numpy as np
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 I should do, or if there is another method?

CodePudding user response:

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)
  • Related