装 NumPy

pip install numpy

创建数组

import numpy as np

a = np.array([1, 2, 3, 4])
b = np.array([[1, 2, 3], [4, 5, 6]])      # 二维

print(a.shape, a.dtype)     # (4,) int64
print(b.shape, b.dtype)     # (2, 3) int64

常用快捷创建

np.zeros((2, 3))          # 全 0
np.ones((2, 3))           # 全 1
np.arange(0, 10, 2)       # [0, 2, 4, 6, 8]
np.linspace(0, 1, 5)      # [0, 0.25, 0.5, 0.75, 1]
np.random.randn(3, 3)     # 标准正态分布
np.eye(3)                 # 3x3 单位矩阵

dtype:数据类型

a = np.array([1, 2, 3], dtype=np.float32)
print(a.dtype)            # float32

# 转换
b = a.astype(np.int32)

常见 dtype:int32 / int64 / float32 / float64 / bool。深度学习多用 float32

索引和切片

a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
a[3]            # 3
a[2:5]          # [2, 3, 4]
a[::2]          # [0, 2, 4, 6, 8]
a[-1]           # 9

# 二维
m = np.arange(12).reshape(3, 4)
# [[0  1  2  3]
#  [4  5  6  7]
#  [8  9 10 11]]
m[1, 2]         # 6
m[:, 1]         # [1, 5, 9]   第二列
m[1, :]         # [4, 5, 6, 7] 第二行
m[1:, 1:3]      # 子矩阵

布尔索引(超好用)

a = np.array([1, 2, 3, 4, 5])
mask = a > 3                # array([False, False, False,  True,  True])
a[mask]                     # array([4, 5])
a[a > 3]                    # 一行写法

数学运算(按元素)

a = np.array([1, 2, 3])
b = np.array([10, 20, 30])

a + b           # [11 22 33]
a * b           # [10 40 90]
a ** 2          # [1 4 9]
np.sqrt(a)      # [1. 1.41 1.73]

没有循环,自动按元素运算——这就是 NumPy 的魔力。

聚合

m = np.arange(12).reshape(3, 4)

m.sum()             # 66       全局求和
m.sum(axis=0)       # [12 15 18 21]   按列求和(沿行方向)
m.sum(axis=1)       # [6 22 38]       按行求和(沿列方向)
m.mean()
m.max(axis=1)
m.argmax(axis=1)    # 每行最大值的位置

形状变换

a = np.arange(12)
a.reshape(3, 4)         # 3x4
a.reshape(2, 2, 3)      # 三维
a.reshape(-1, 4)        # -1 表示自动算(这里 = 3)
a.T                     # 转置(仅 2D 有意义)
a.flatten()             # 展平成 1D

下一篇讲 NumPy 进阶:广播和向量化。