1

I am puzzled why this is not working:

a = np.array([[1,2,3], [1,20, 30], [4, 5, 6]])

a[a[:, 0] == 1][:, 2] = [9999, 9999]

I expect:

a = [[1, 2, 9999], [1, 20, 9999], [4, 5, 6]]

But nothing changes. What is wrong?

1
  • 4
    AFAIK, u = a[a[:, 0] == 1] copies the data because a[:, 0] == 1 is an advanced index. Next, u[:, 2] indexes into that copy, so assignment affects the copy, not the original array. Commented Sep 19, 2022 at 13:27

1 Answer 1

1

As explained in the comments, you're currently updating an in-memory copy, not your original array.

You can use direct indexing:

a[a[:,0]==1, 2] = 9999

or with numpy.where (not necessary here):

a[np.where(a[:,0]==1)[0], 2] = 9999

updated a:

array([[   1,    2, 9999],
       [   1,   20, 9999],
       [   4,    5,    6]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.