Skip to content

创建 NumPy ndarray 对象

NumPy 用于处理数组。 NumPy 中的数组对象称为 ndarray

我们可以使用 array() 函数创建一个 NumPy ndarray 对象。

python
arr = np.array([1, 2, 3, 4, 5])
arr = np.array((1, 2, 3, 4, 5))# arr.ndim = 1
arr = np.array({1, 2, 3, 4, 5})# arr.ndim = 0

由上可知,可以使用列表或者元组构建数组

检查维数?

NumPy 数组提供了 ndim 属性,该属性返回一个整数,该整数会告诉我们数组有多少维。

python
import numpy as np

a = np.array(1)
b = np.array([a, a+1, a+2])
c = np.array([b, b+1, b+2])
d = np.array([c, c+1, c+2])

print(a.ndim)# 0
print(b.ndim)# 1
print(c.ndim)# 2
print(d.ndim)# 3

更高维的数组

数组可以拥有任意数量的维。

在创建数组时,可以使用 ndmin 参数定义维数。

python
import numpy as np

arr = np.array([1, 2, 3, 4], ndmin=5)

print(arr)
print('number of dimensions :', arr.ndim)

# [[[[[1 2 3 4]]]]]
# number of dimensions : 5

访问数组元素

python
import numpy as np

a = np.array(1)
b = np.array([a, a+1, a+2])
c = np.array([b, b+1, b+2])
d = np.array([c, c+1, c+2])

print(a)			# 1
print(b[1])			# 2
print(c[1][1])		# 3
print(c[1, 1])		# 3
print(d[1][1][1])  	# 4
print(d[1, 1, 1])  	# 4

负索引

python
print(b[-1])		# 3
print(c[-1][-1])	# 5
print(c[-1, -1])	# 5
print(d[-1][-1][-1])# 7
print(d[-1, -1, -1])# 7

索引范围

python
arr[start:end]
arr[start:end:step]# 可以定义步长

如果我们不传递 start,则将其视为 0。

如果我们不传递 end,则视为该维度内数组的长度。

如果我们不传递 step,则视为 1。

实例

从两个元素裁切索引 1 到索引 4(不包括),这将返回一个 2-D 数组:

python
import numpy as np

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(arr[0:2, 1:4])

输出

python
[[2 3 4]
 [7 8 9]]