幻想索引与Numpy中的视图第二部分 [英] Fanccy Indexing vs View in Numpy part II

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

问题描述

花式索引与Numpy中的视图

在回答这个方程式时:解释了不同的习语会产生不同的结果.

In an answer to this equation: is is explained that different idioms will produce different results.

使用习惯式索引来选择值并将这些值设置为同一行中的新值,这意味着原始对象中的值将被更改.

Using the idiom where fancy indexing is to chose the values and said values are set to a new value in the same line means that the values in the original object will be changed in place.

但是下面的最后一个示例:

However the final example below:

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

最后的练习"

该示例似乎使用了相同的习惯用法:

The example appears to use the same idiom:

a [x,:] [:, y] = 100

a[x, :][:, y] = 100

,但根据x是切片还是奇特的索引,它仍然会产生不同的结果(见下文):

but it still produces a different result depending on whether x is a slice or a fancy index (see below):

a = np.arange(12).reshape(3,4)
ifancy = [0,2]
islice = slice(0,3,2)
a[islice, :][:, ifancy] = 100
a
#array([[100,   1, 100,   3],
#       [  4,   5,   6,   7],
#       [100,   9, 100,  11]])

a = np.arange(12).reshape(3,4)
ifancy = [0,2]
islice = slice(0,3,2)
a[ifancy, :][:, islice] = 100  # note that ifancy and islice are interchanged here
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

我的直觉是,如果第一组花式索引是一个切片,则它将对象视为视图,因此原始对象中的值会更改.

My intuition is that if the first set of fancy indexes is a slice it treats the object like a view and therefore the values in the orignal object are changed.

在第二种情况下,第一组花式索引本身就是花式索引,因此它将对象视为创建原始对象副本的花式索引.这意味着复制对象的值更改时,原始对象不会更改.

Whereas in the second case the first set of fancy indexes is itself a fancy index so it treats the object as a fancy index creating a copy of the original object. This then means that the original object is not changed when the values of the copy object are changed.

我的直觉正确吗?

该示例提示人们应该考虑 getitem setitem 的缺点,有人可以用这种方式向我正确解释吗?

The example hints that one should think of the sqeuence of getitem and setitem can someone explain it to my properly in theis way?

推荐答案

Python分别评估每组[]. a[x, :][:, y] = 100是2个操作.

Python evaluates each set of [] separately. a[x, :][:, y] = 100 is 2 operations.

temp = a[x,:]           # getitem step
temp[:,y] = 100         # setitem step

第二行是否最终修改a取决于temp是视图还是副本.

Whether the 2nd line ends up modifying a depends on whether temp is a view or copy.

请记住,numpy是Python的附加组件.它不会修改基本的Python语法或解释.

Remember, numpy is an addon to Python. It does not modify basic Python syntax or interpretation.

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

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