Home > Back-end >  Replacing elements in multidimensional numpy array based on condition
Replacing elements in multidimensional numpy array based on condition

Time:09-20

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?

CodePudding user response:

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