Numpy - 高级索引
NumPy 中的高级索引
NumPy 中的高级索引是一种使用特定索引的数组或列表从数组中选择多个元素的方法,其中索引用于表示元素在数组中的位置。您可以根据需要一次选择多个元素,而无需逐个选择元素。
这就像给数组一个您想要的"索引"列表,它会直接返回这些值,从而使数据处理更加快捷。
高级索引是简单索引的高级形式。在简单索引中,我们使用整数访问单个元素或切片,而高级索引使用整数数组或列表访问多个元素。它返回一个独立于原始数组的新数组。
花式索引允许您使用以下方式访问多个元素 -
另一个 NumPy 数组
Python 列表
示例:简单索引
让我们创建一个一维数组,通过其位置访问单个元素。在下面的代码中,arr[3] 访问数组中索引为 3(第四个位置)的元素,即 60。
import numpy as np x = np.array([50, 90, 70, 60, 40, 100]) print("使用简单索引:" ,x[3])
以下是上述代码的输出 -
使用简单索引:60
使用 NumPy 数组进行复杂的索引
我们使用 arange() 函数创建一个包含 20 到 30 的数字的一维数组,然后我们将创建第二个 NumPy 数组,用于索引位于一次。
在下面的代码中,我们创建了第二个数组,其中包含用于访问多个元素的索引,即 3、4、6,这些位置上的元素是 23、24、26。
import numpy as np x = np.arange(20, 31) print(x) arr = np.array([ 3, 4, 6]) print("3、4、6 位置上的元素是: " , x[arr])
以下是上述代码的输出 -
[20 21 22 23 24 25 26 27 28 29 30] 3、4、 6 个位置分别是: [23 24 26]
使用 Python 列表进行复杂的索引
我们使用 randint 函数创建一个一维数组,该函数会生成随机整数。然后,我们将使用 Python 列表来存储要访问的位置。这里 [1, 0, 2] 存储在 indices 中,然后我们将使用 indices 列表来访问该数组。
import numpy as np array = np.random.randint(10, 59, size = 10) print(array) indices = [1, 0, 2] print("使用 Python 列表访问多个元素: ", array[indices])
以下是上述代码的输出 -
[32 57 48 26 47 32 38 35 30 36] 使用 Python 列表访问多个元素: [57 32 48]
使用花式索引
在本例中,我们使用 arange() 函数构建了一个包含 1 到 10 的数字的一维数组。这里我们需要访问的元素以二维形式指定。在花式索引中,结果的形状由索引数组的形状反映。以下是代码:
import numpy as np x = np.arange(1, 10) indices = np.array([[5, 3], [4, 5]]) new_2D_arr = x[indices] print(new_2D_arr)
以下是上述代码的输出 -
[[6 4] [5 6]]
二维 NumPy 数组中的花式索引
在下面的示例中,我们使用花式索引从二维数组中选择多个元素。行和列的索引以列表形式提供,代码从二维数组中选择指定的元素。
import numpy as np x = np.arange(12) x_2D = x.reshape(3,4) row_indices = [ 1, 2] col_indices = [0, 2] selected_indices = x_2D[row_indices, col_indices] print("二维数组为: ", x_2D) print("选定的元素为: ", selected_indices)
以下是上述代码的输出 -
二维数组为: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] 选定元素为: [ 4 10]
三维 NumPy 数组中的花式索引
在下面的示例中,我们创建了一个三维数组,并指定了depth_indices、row_indices、col_indices,以便使用花式索引选择特定的多个元素。
import numpy as np x = np.arange(27) x_3D = x.reshape(3, 3, 3) depth_indices = [0, 1] row_indices = [ 1, 2] col_indices = [0, 2] selected_indices = x_3D[depth_indices, row_indices, col_indices] print("三维数组是: ", x_3D) print("三维数组中的选定元素: ", selected_indices)
以下是上述代码的输出 -
三维数组为: [[[ 0 1 2] [ 3 4 5] [ 6 7 8]] [[ 9 10 11] [12 13 14] [15 16 17]] [[18 19 20] [21 22 23] [24 25 26]]] 三维数组中的选定元素: [ 3 17]
使用负索引的花式索引
借助花式索引,我们可以使用负索引从数组末尾访问多个元素数组。以下是使用负索引进行花式索引的示例。
import numpy as np x = np.arange(10) indices = np.array([-1, -2, -3]) print("选定元素:", x[indices])
以下是上述代码的输出 -
选定元素:[9 8 7]