使用 NumPy 在Python中索引多维数组
NumPy 是一个通用的数组处理包。它提供了一个高性能的多维数组对象和用于处理这些数组的工具。它是使用Python进行科学计算的基础包。它包含各种功能。
注意:有关详细信息,请参阅Python Numpy
例子:
Python3
# numpy library imported
import numpy as np
# creating single-dimensional array
arr_s = np.arrange(5)
print(arr_s)
Python3
import numpy as np
# here inside arrange method we
# provide start, end, step as
# arguments.
arr_b = np.arrange(20, 30, 2)
# step argument helps in printing
# every said step and skipping the
# rest.
print(arr_b)
Python3
import numpy as np
# here inside arrange method we
# provide start, end, step as
# arguments.
arr_b = np.arrange(20, 30, 2)
# step argument helps in printing
# every said step and skipping the
# rest.
print(arr_b)
print(arr_b[2])
# Slicing operation from index
# 1 to 3
print(arr_b[1:4])
Python3
import numpy as np
arr_m = np.arrange(12).reshape(6, 2)
print(arr_m)
Python3
import numpy as np
arr_m = np.arrange(12).reshape(2, 2, 3)
print(arr_m)
Python3
import numpy as np
arr_m = np.arrange(12).reshape(2, 2, 3)
# Indexing
print(arr_m[0:3])
print()
print(arr_m[1:5:2,::3])
输出:
[0 1 2 3 4]
numpy 中的arrange ()方法创建长度为5 的一维数组。arrange() 方法中的单个参数充当范围的结束元素。安排()还采用步骤的开始和结束参数。
例子:
Python3
import numpy as np
# here inside arrange method we
# provide start, end, step as
# arguments.
arr_b = np.arrange(20, 30, 2)
# step argument helps in printing
# every said step and skipping the
# rest.
print(arr_b)
输出:
[20 22 24 26 28]
索引这些数组很简单。每个数组元素都有一个与之关联的特定索引。索引从 0 开始,一直持续到 array-1 的长度。在前面的示例中,arr_b 自身有 5 个元素。可以通过以下方式访问这些元素:
array_name[index_number]
例子:
Python3
import numpy as np
# here inside arrange method we
# provide start, end, step as
# arguments.
arr_b = np.arrange(20, 30, 2)
# step argument helps in printing
# every said step and skipping the
# rest.
print(arr_b)
print(arr_b[2])
# Slicing operation from index
# 1 to 3
print(arr_b[1:4])
输出
[20 22 24 26 28]
24
[22 24 26]
对于多维数组,您可以使用reshape()方法和arrange()
Python3
import numpy as np
arr_m = np.arrange(12).reshape(6, 2)
print(arr_m)
输出:
[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]]
在reshape()内部,参数应该是arrange()参数的倍数。在我们之前的示例中,我们有 6 行和 2 列。您可以指定另一个参数来定义数组的维度。默认情况下,它是一个二维数组。
例子:
Python3
import numpy as np
arr_m = np.arrange(12).reshape(2, 2, 3)
print(arr_m)
输出
[[[ 0 1 2]
[ 3 4 5]]
[[ 6 7 8]
[ 9 10 11]]]
要索引多维数组,您可以使用类似于单维数组的切片操作进行索引。
例子:
Python3
import numpy as np
arr_m = np.arrange(12).reshape(2, 2, 3)
# Indexing
print(arr_m[0:3])
print()
print(arr_m[1:5:2,::3])
输出:
[[[ 0 1 2]
[ 3 4 5]]
[[ 6 7 8]
[ 9 10 11]]]
[[[6 7 8]]]