简体   繁体   中英

Replacing elements in multidimensional numpy array based on condition

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM