task 02:索引

it2024-05-12  51

1 整数索引

要获取数组的单个元素,指定元素的索引即可。

import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7, 8]) print(x[2]) # 3

2 切片索引

切片操作是指抽取数组的一部分元素生成新数组。对 python 列表进行切片操作得到的数组是原数组的副本,而对 Numpy 数据进行切片操作得到的数组则是指向相同缓冲区的视图。 如果想抽取(或查看)数组的一部分,必须使用切片语法,也就是,把几个用冒号( start:stop:step )隔开的数字置于方括号内。

import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7, 8]) print(x[0:2]) # [1 2] print(x[1:5:2]) # [2 4] print(x[2:]) # [3 4 5 6 7 8] print(x[:2]) # [1 2] print(x[-2:]) # [7 8]

通过对每个以逗号分隔的维度执行单独的切片,你可以对多维数组进行切片。因此,对于二维数组,我们的第一片定义了行的切片,第二片定义了列的切片。

import numpy as np x = np.array([ [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33, 34, 35]]) print(x) # [[11 12 13 14 15] # [16 17 18 19 20] # [21 22 23 24 25] # [26 27 28 29 30] # [31 32 33 34 35]]

3 dots 索引

NumPy 允许使用… 表示足够多的冒号来构建完整的索引列表。

import numpy as np x = np.random.randint(1, 100, [2, 2, 3]) print(x) # [[[ 5 64 75] # [57 27 31]] # [[68 85 3] # [93 26 25]]] print(x[1, ...]) # [[68 85 3] # [93 26 25]] print(x[..., 2]) # [[75 31] # [ 3 25]]

4 整数数组索引

方括号内传入多个索引值,可以同时选择多个元素。

import numpy as np x = np.array([ [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33, 34, 35]]) r = [0, 1, 2] print(x[r]) # [[11 12 13 14 15] # [16 17 18 19 20] # [21 22 23 24 25]] r = [0, 1, 2] c = [2, 3, 4] y = x[r, c] print(y) # [13 19 25] import numpy as np x = np.array([ [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33, 34, 35]]) r = np.array([[0,0 ], [4,4]]) c = np.array([[0, 4], [0, 4]]) y = x[r, c] print(y) # [[11 15] # [31 35]]

numpy. take(a, indices, axis=None, out=None, mode=‘raise’) Take elements from an array along an axis.

import numpy as np x = np.array([ [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33, 34, 35]]) r = [0, 1, 2] print(np.take(x, r, axis=0)) # [[11 12 13 14 15] # [16 17 18 19 20] # [21 22 23 24 25]]

5 布尔索引

我们可以通过一个布尔数组来索引目标数组。

import numpy as np x = np.array([1, 2, 3, 4, 5, 6, 7, 8]) y = x > 5 print(y) # [False False False False False True True True] print(x[x > 5]) # [6 7 8] x = np.array([np.nan, 1, 2, np.nan, 3, 4, 5]) y = np.logical_not(np.isnan(x)) print(x[y]) # [1. 2. 3. 4. 5.]
最新回复(0)