Skip to content

NumPy ndarray API

NumPy provides high-performance multidimensional ndarray and vectorized numerical computing capabilities.

1 class · 8 methods

ndarray

8 methods

数组创建、形状变换与数值运算的核心 API。

np.array(object, dtype=None)

从列表或嵌套序列创建 ndarray。

Parameters

NameTypeDescription
objectlist | array_like输入数据
dtypedtype期望的数据类型

Returns

ndarray — 多维数组

Example

numpy
import numpy as np

a = np.array([1, 2, 3], dtype="float64")
b = np.array([[1, 2], [3, 4]])
print(a.dtype, b.shape)
np.zeros(shape) / np.ones(shape)

创建指定形状的全零或全一数组。

Parameters

NameTypeDescription
shapeint | tuple数组形状

Returns

ndarray — 全零/全一数组

Example

numpy
import numpy as np

z = np.zeros((2, 3))
o = np.ones(5)
print(z)
print(o)
np.arange(start, stop, step)

返回给定区间内等差数值组成的一维数组。

Parameters

NameTypeDescription
startnumber起始值(含)
stopnumber结束值(不含)
stepnumber步长

Returns

ndarray — 等差数列数组

Example

numpy
import numpy as np

x = np.arange(0, 10, 2)
print(x)  # [0 2 4 6 8]
np.reshape(a, newshape)

在不改变数据的前提下改变数组形状。

Parameters

NameTypeDescription
arrayndarray输入数组
newshapeint | tuple目标形状,-1 自动推断

Returns

ndarray — 重塑后的数组

Example

numpy
import numpy as np

a = np.arange(6)
b = a.reshape(2, 3)
print(b)
ndarray.shape

返回或设置数组的形状(各维度大小的元组)。

Returns

tuple[int] — 数组形状

Example

numpy
import numpy as np

a = np.zeros((3, 4, 5))
print(a.shape)        # (3, 4, 5)
print(a.shape[0])     # 3
ndarray.dtype

返回数组元素的数据类型。

Returns

dtype — 元素数据类型对象

Example

numpy
import numpy as np

a = np.array([1, 2, 3])
print(a.dtype)        # int64
b = a.astype("float32")
print(b.dtype)
np.dot(a, b)

计算两个数组的点积(向量内积或矩阵乘法)。

Parameters

NameTypeDescription
andarray左侧数组
bndarray右侧数组

Returns

ndarray | number — 点积结果

Example

numpy
import numpy as np

A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print(np.dot(A, B))
np.sum(a, axis=None)

沿指定轴对数组元素求和,默认对所有元素求和。

Parameters

NameTypeDescription
arrayndarray输入数组
axisint | tuple | None求和的轴,None 表示全部

Returns

ndarray | number — 求和结果

Example

numpy
import numpy as np

a = np.array([[1, 2], [3, 4]])
print(a.sum())            # 10
print(a.sum(axis=0))      # [4 6]
print(a.sum(axis=1))      # [3 7]