1

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.

asked Aug 25, 2022 at 13:46
1
  • 1
    x[x[:,2] == 3][:,2] does not do what you think it does: x[x[:,2] == 3] creates a new temporary array and not a view. It is not possible for Numpy do return a view because it would not be efficient. You need to use np.where or np.argwhere so to create a new array based on the x[:,2] == 3 result. Commented Aug 25, 2022 at 13:50

2 Answers 2

1

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
answered Aug 25, 2022 at 13:54
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, that is very unintuitive, but it makes sense.
or (less readable) as x[:,2][x[:,2] == 3] = 5
0

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
answered Aug 25, 2022 at 13:52

1 Comment

I think this is a good solution, but not for my purpose (which I should have further specified) because I don't want to edit the first two columns

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.