ndarray
8 methods数组创建、形状变换与数值运算的核心 API。
np.array(object, dtype=None)从列表或嵌套序列创建 ndarray。
Parameters
| Name | Type | Description |
|---|---|---|
| object | list | array_like | 输入数据 |
| dtype | dtype | 期望的数据类型 |
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
| Name | Type | Description |
|---|---|---|
| shape | int | 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
| Name | Type | Description |
|---|---|---|
| start | number | 起始值(含) |
| stop | number | 结束值(不含) |
| step | number | 步长 |
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
| Name | Type | Description |
|---|---|---|
| array | ndarray | 输入数组 |
| newshape | int | 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]) # 3ndarray.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
| Name | Type | Description |
|---|---|---|
| a | ndarray | 左侧数组 |
| b | ndarray | 右侧数组 |
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
| Name | Type | Description |
|---|---|---|
| array | ndarray | 输入数组 |
| axis | int | 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]