简体   繁体   中英

How to return an array with values at given indices replaced by new values?

I can set values in an array with given indices like so:

>>> a=np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> a[[1,3,4]]=[-1,-2,-3]
>>> a
array([ 0, -1,  2, -2, -3])

This also works with a boolean mask. The functions np.put and np.putmask both do the same thing, but do so by modifying the original array. Is there a way to do this without modifying the original array or copying it? An example of what I'm looking for:

>>> a=np.arange(5)
>>> np.foo(a, [1,3,4], [-1,-2,-3])
array([ 0, -1,  2, -2, -3])
>>> a
array([0, 1, 2, 3, 4])

Just change the elements on a copy of the array.

a = np.arange(5)
a
>np.array([0, 1, 2, 3, 4])
b = np.array(a)
b[[1, 3, 4]] = [-1, -2, -3]
a
>np.array([0, 1, 2, 3, 4])
b
>np.array([0, -1, 2, -2, -3])

EDIT: Note that Python follows Command-query separation very strictly, except in cases that are obviously not going to do any harm (such as with list.pop ). Thus, it is neither encouraged nor possible to both change items in a list and return that list. However, seeing as you would most likely have to store the altered list in some way, there is negligible performance slowdown from first copying the original list and then changing the elements in that list.

If you really really wanted to, you can probably override the __setitem__ method of np.ndarray or create a new subclass of np.ndarray and override __setitem__ for that instead, but again, there isn't really any need to do that.

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