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 位置的元素是:\n" , 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 列表访问多个元素:\n", 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("二维数组是:\n", x_2D)
print("选中的元素是:\n", selected_indices)
以上代码的输出如下:
二维数组是: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] 选中的元素是: [ 4 10]
3D NumPy 数组中的 Fancy Indexing
在下面的示例中,我们创建了一个 3D 数组,并指定了 depth_indices、row_indices、col_indices 来使用 fancy indexing 选择特定的多个元素。
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("3D array is :\n", x_3D)
print("selected elements in the 3D array : \n", selected_indices)
以上代码的输出如下 −
3D array is : [[[ 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]]] selected elements in the 3D array : [ 3 17]
使用负索引的 Fancy Indexing
借助 fancy indexing,我们可以使用负索引从数组末尾访问多个元素。以下是使用负索引的 fancy indexing 示例。
import numpy as np
x = np.arange(10)
indices = np.array([-1, -2, -3])
print("Selected elements:", x[indices])
以上代码的输出如下 −
Selected elements: [9 8 7]