Home > Net >  Numpy array remains unchanged even after assignment
Numpy array remains unchanged even after assignment

Time:08-26

Suppose I have the matrix x. x has 3 columns and arbitrarily many rows. I want to grab all the rows that have a certain value and change this value for all these rows. Below is an example as well as my attempt to do this.

x = np.array(
        [[-3.1913035 , -1.34344639, 0],
        [-2.54438272, -1.88907741, 1],
        [ 2.12029563,  2.51443883, 3],
        [-2.98150865, -1.53789653, 3],
        [-1.94179128, -3.1429703, 3 ]])
x[x[:,2] == 3][:,2] = 5 # the values 3 and 5 are strictly examples.
print(x)

Printing x on the last line displays an unchanged matrix. I expect x to look like

np.array(
        [[-3.1913035 , -1.34344639, 0],
        [-2.54438272, -1.88907741, 1],
        [ 2.12029563,  2.51443883, 5],
        [-2.98150865, -1.53789653, 5],
        [-1.94179128, -3.1429703, 5 ]])

Can I please have some help? I have been searching up this problem for hours but I have not found the solution.

CodePudding user response:

A way to do what you want is to grab only the column you want to change and then change it.

y = x[:,2]
y[y==3] = 5

CodePudding user response:

If you want to replace all elements that matches 3 then this might be helpful.

x[x == 3] = 5

This might be useful to specify column criteria in

np.ix_(row_criteria, col_criteria)

x[np.ix_(x[:,2]==3, [2])] = 5
  • Related