Why does an assignment for double-sliced numpy arrays not work?

只谈情不闲聊 提交于 2019-12-21 07:58:29

问题


why do the following lines not work as I expect?

import numpy as np
a = np.array([0,1,2,1,1])
a[a==1][1:] = 3
print a
>>> [0 1 2 1 1]
# I would expect [0 1 2 3 3]

Is this a 'bug' or is there another recommended way to this?

On the other hand, the following works:

a[a==1] = 3
print a
>>> [0 3 2 3 3]

Cheers, Philipp


回答1:


It appears you simply can't do an assignment through a double-slice like that.

This works though:

a[numpy.where(a==1)[0][1:]] = 3



回答2:


It's related to how fancy indexing works. There is a thorough explanation here. It is done this way to allow inplace modification with fancy indexing (ie a[x>3] *= 2). A consequence of this is that you can't assign to a double index as you have found. Fancy indexing always returns a copy rather than a view.




回答3:


Because the a[a==1] part isn't actually a slice. It creates a new array. It makes sense when you think about it-- you're only taking the elements that satisfy the boolean condition (like a filter operation).




回答4:


This does what you want

a[2:][a[2:]==1]=3


来源:https://stackoverflow.com/questions/1687566/why-does-an-assignment-for-double-sliced-numpy-arrays-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!