为什么双切片 numpy 数组的赋值不起作用?
为什么以下几行不能按我的预期工作?
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]
这是一个“错误”还是有其他推荐的方法?
另一方面,以下作品:
a[a==1] = 3
print a
>>> [0 3 2 3 3]
干杯,菲利普
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这与花式索引的工作方式有关。 此处有详尽的解释。这样做是为了允许使用花式索引进行就地修改(即
a[x>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.看来你根本无法通过这样的双切片来完成作业。
这虽然有效:
It appears you simply can't do an assignment through a double-slice like that.
This works though:
因为 a[a==1] 部分实际上不是切片。它创建一个新数组。当您仔细考虑时,这是有道理的——您只获取满足布尔条件的元素(如过滤操作)。
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).
这就是你想要的
This does what you want
根据条件,使用 np.where 可能很困难。
我建议独立创建一个索引数组:
Depending on the conditions using np.where can be difficult.
I would suggest creating an indexing array independently :