In python, x[(exp1, exp2, …, expN)] is equivalent to x[exp1, exp2, …, expN]. (exp1, exp2, …, expN) is called selection tuple.
不同dim用逗号","隔开
对某一dim切片取索引用i:j:k
- i是起始索引,j是结束索引,k是间隔(每k个元素取一个)
- 如果i或j是负数,就是倒数第|i|或|j|个数,index = n + i and n + j where n is the number of elements in the corresponding dimension
- 如果k是负数,逆向取索引,从右往左(stepping go towards smaller indices)
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
x[1:7:2]
array([1, 3, 5])
x[-2:10]
array([8, 9])
x[-3:3:-1]
array([7, 6, 5, 4])
- ::与:和相同,表示选择沿此轴的所有index
x[5:]
array([5, 6, 7, 8, 9])
- 如果ndarray有N个维度,但我们只写了对前n个维度的切片索引,则对后续的任何维度都假设为:(全部取,不切片)。
x = np.array([[[1],[2],[3]], [[4],[5],[6]]])
x.shape
(2, 3, 1)
x[1:2] # 只切片第一维度
array([[[4],
[5],
[6]]])
- 切片还可以包括省略号 …,来使选择元组的长度与数组的维度相同。在selection tuple(就是a[ ]中)声明的dim切片,用…来代指其他dim都取。
>>> a = np.array([[1,2,3,4],[3,4,5,6],[4,5,6,7]])
>>> a[...,1].shape
(3,)
>>> a[...,1]
array([2, 4, 5])
>>> a[...,1:].shape
(3, 3)
>>> a[...,1:]
array([[2, 3, 4],
[4, 5, 6],
[5, 6, 7]])
>>> a[1,...]
array([3, 4, 5, 6])
- newaxis:增加一个unit-length dim
reference:
https://numpy.org/doc/stable/reference/arrays.indexing.html
本文介绍Python中NumPy数组的高级索引方法,包括使用元组进行多维索引、切片操作详解及省略号(...)的使用,并演示如何通过这些技巧高效地访问和操作数组元素。

4029

被折叠的 条评论
为什么被折叠?



