为什么双切片 numpy 数组的赋值不起作用?

发布于 2024-08-09 18:39:47 字数 306 浏览 8 评论 0原文

为什么以下几行不能按我的预期工作?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

┈┾☆殇 2024-08-16 18:39:47

这与花式索引的工作方式有关。 此处有详尽的解释。这样做是为了允许使用花式索引进行就地修改(即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.

淡看悲欢离合 2024-08-16 18:39:47

看来你根本无法通过这样的双切片来完成作业。

这虽然有效:

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

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
美羊羊 2024-08-16 18:39:47

因为 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).

千柳 2024-08-16 18:39:47

这就是你想要的

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

This does what you want

a[2:][a[2:]==1]=3
耳钉梦 2024-08-16 18:39:47

根据条件,使用 np.where 可能很困难。
我建议独立创建一个索引数组:

a = np.array([0,1,2,1,1])
pos_to_change = np.arange(0,len(a))[a==1][1:]
a[pos_to_change] = 3
print(a)
>>> array([0, 1, 2, 3, 3])

Depending on the conditions using np.where can be difficult.
I would suggest creating an indexing array independently :

a = np.array([0,1,2,1,1])
pos_to_change = np.arange(0,len(a))[a==1][1:]
a[pos_to_change] = 3
print(a)
>>> array([0, 1, 2, 3, 3])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文