我正在尝试理解这篇文章的一个具体部分。
高级索引的定义意味着
x[(1,2,3),]
和x[(1,2,3)]
有根本的区别。后者等同于x[1,2,3]
,将触发基本选择,而前者将触发高级索引。请确保理解其原因。
我已经尝试了以下代码。
>>> import numpy as np
>>> a = np.arange(50).reshape(5,10)
>>> b = a[(2,2)]
>>> bb = a[(2,2),]
>>> a[2,2] = 50 # a[2,2] was 22 in the first place
>>> b
22 # this outcome confuses me!
我认为b = a[(2,2)]
会得到一个视图,所以当我改变a[2,2]
时,它也会改变。
bb = a[(2,2),]
会接收副本,因此即使我对a进行操作,也不会发生任何事情。
但是当我将a[2,2]
从22改为50时
我期望b = a[(2,2)]
会改变为50,而bb = a[(2,2),]
仍然保持不变。
这其中有什么问题吗?我是否理解有误或者漏掉了一些重要的东西?
如果是这样,请指正我,非常感谢!
a[2,2,...]
触发了花式索引,因为...
实际上意味着“包括所有其他维度”,即使没有其他维度,它也算作一个切片。由于您正在混合切片和索引,因此被认为是“花式”并返回一个视图。这可能是最好的解决方案,因为它不需要squeeze()
。 - Daniel F:
will only trigger fancy indexing if there is actually a dimension there. If you doa[2,2,:]
you'll get anIndexError
becasue there is no third dimension ina
- Daniel FNone
adds another dimension (it's the same asnp.newaxis
but shorter to write) which is considered a slice. You then get rid of that dimension withsqueeze()
- Daniel F