Numpy中的N维数组(ndarray)
Numpy 中的数组是一个元素表(通常是数字),所有元素类型相同,由正整数元组索引。在 Numpy 中,数组的维数称为数组的秩。给出数组沿每个维的大小的整数元组称为数组的形状。Numpy 中的数组类称为ndarray。Numpy 数组中的元素可以使用方括号访问,并且可以使用嵌套的 Python 列表进行初始化。
例子 :
[[ 1, 2, 3],
[ 4, 2, 5]]
Here, rank = 2 (as it is 2-dimensional or it has 2 axes)
First dimension(axis) length = 2, second dimension has length = 3
overall shape can be expressed as: (2, 3)
# 演示基本数组特征的 Python 程序
import numpy as np
# 创建数组对象
arr = np.array( [[ 1, 2, 3],
[ 4, 2, 5]] )
# arr 对象的打印类型
print("Array is of type: ", type(arr))
# 打印数组维度(轴)
print("No. of dimensions: ", arr.ndim)
# 阵列的打印形状
print("Shape of array: ", arr.shape)
# 数组的打印大小(元素总数)
print("Size of array: ", arr.size)
# 打印数组中元素的类型
print("Array stores elements of type: ", arr.dtype)
输出 :
Array is of type: <class 'numpy.ndarray'>
No. of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int64
数组创建
在 NumPy 中有多种创建数组的方法。
- 例如,您可以使用array函数从常规 Python列表或元组创建一个数组。 结果数组的类型是从序列中元素的类型推导出来的。****
- 通常,数组的元素最初是未知的,但它的大小是已知的。因此,NumPy 提供了几个函数来创建具有初始占位符内容的数组。这些最大限度地减少了增长阵列的必要性,这是一项昂贵的操作。
例如: np.zeros、np.ones、np.full、np.empty 等。 - 为了创建数字序列,NumPy 提供了一个类似于 range 的函数,它返回数组而不是列表。
- arange: 返回给定间隔内均匀分布的值。步长是指定的。
- linspace: 返回给定间隔内均匀分布的值。编号_ 的元素被返回。
- 重塑数组: 我们可以使用reshape方法来重塑数组。考虑一个形状为 (a1, a2, a3, ..., aN) 的数组。我们可以重新整形并将其转换为另一个形状为 (b1, b2, b3, ..., bM) 的数组。唯一需要的条件是: