花式索引与Numpy中的视图 [英] Fancy Indexing vs Views in Numpy

查看:89
本文介绍了花式索引与Numpy中的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对附加链接中的文章的另一部分感到困惑:

I'm confused by another part of the article in the attached link:

https://scipy-cookbook.readthedocs.io/items/ViewsVsCopies.html

在但是花哨的索引有时似乎返回视图,不是吗?"

In the section "But fancy indexing does seem to return views sometimes, doesn't it?"

第一个成语:

a = np.arange(10)
a[[1,2]] = 100
a
#array([  0, 100, 100,   3,   4,   5,   6,   7,   8,   9])

第二个成语:

a = numpy.arange(10)
c1 = a[[1,2]]
c1[:] = 100
a
#array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> c1
#array([100, 100])

关于第一个成语如何进行更改,我还是有些困惑?

I'm still a bit confused as to how the first idiom is able to make the changes?

他们解释说,第一个习语不是在 setitem 之前调用 getitem ,但是为什么不这样做呢?

They explain that the first idiom is not calling getitem before setitem but why is it not doing it?

我以为所有花哨的索引都返回数据的副本而不是视图,而与所使用的惯用法无关吗?

I thought that all fancy indexes returned a copy of the data rather than a view irrespective of the idiom used?

尽管花哨的索引并没有创建显示的视图,但仍然可以提供理想的结果,如习惯用语1所示,使用它还是被认为是一种好习惯吗?

Although fancy indexing does not create a view as they demonstrate, as it still gives the desired result is it still considered good practice to use it as shown in idiom 1?

推荐答案

原因是Python的工作方式.

The reason is the way Python works.

第一个语句调用setitem方法,第二个语句调用getitem.第一个不会创建新对象,但是第二个会创建对象(对于花式索引,它将创建用于常规索引的视图).

The first statement calls the setitem method, the second getitem. The first one doesn't create a new object, but the second will (for fancy indexing, it will create a view for regular indexing).

当然,我们希望这种行为,以便我们可以在数组中设置一些非常规"值以及视图不起作用的值.

And of course, we want this behavior so that we can set some values in an array that are not "regular" and where a view would not work.

这篇关于花式索引与Numpy中的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆