第 32 章 NumPy 核心操作
这一章开始,NumPy 才真正变得有意思。
前面我们已经知道:
python
import numpy as np
numbers = np.array([10, 20, 30, 40])但如果你只是把 NumPy 当成一个“更快的 Python list”,其实还没有真正理解它。
NumPy 真正厉害的地方在于:
你可以把一个数组当成一个整体进行计算。
不用自己写 for,不用一个元素一个元素地处理。
例如:
python
numbers * 2就可以一次性把所有元素乘以 2:
text
[20 40 60 80]这背后涉及几个非常重要的概念:
- 数组运算
- 广播
- 聚合
- 矩阵
- 线性代数
这些东西也是后面学习 Pandas、机器学习、科学计算的重要基础。
32.1 数组运算
先从最简单的问题开始。
假设我们有两个数组:
python
import numpy as np
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])我们希望:
text
1 + 10
2 + 20
3 + 30Python list 会怎么样?
python
a = [1, 2, 3]
b = [10, 20, 30]
a + b结果不是:
text
[11, 22, 33]而是:
python
[1, 2, 3, 10, 20, 30]因为 Python 的 list + list 表示:
拼接两个列表。
NumPy 的数组则完全不同:
python
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
a + b得到:
text
[11 22 33]NumPy 把这个操作理解成:
text
[1 + 10,
2 + 20,
3 + 30]也就是逐元素运算。
32.1.1 加法
python
a + btext
[11 22 33]32.1.2 减法
python
b - atext
[9 18 27]32.1.3 乘法
这里特别容易犯错。
python
a * b结果是:
text
[10 40 90]也就是:
text
1 × 10
2 × 20
3 × 30这不是矩阵乘法。
NumPy 中:
python
a * b表示逐元素乘法。
矩阵乘法我们后面再讲。
32.1.4 除法
python
b / a结果:
text
[10. 10. 10.]注意结果通常会变成浮点数。
32.1.5 和数字运算
NumPy 数组还可以直接和一个数字运算:
python
numbers = np.array([10, 20, 30])
numbers + 5结果:
text
[15 25 35]你没有写:
python
for number in numbers:
...但 NumPy 帮你完成了。
同样:
python
numbers * 2text
[20 40 60]这就是 NumPy 非常重要的思想:
把“对每个元素做什么”,变成“对整个数组做什么”。
32.2 广播
广播(Broadcasting)是 NumPy 最重要的概念之一。
刚才我们写:
python
numbers + 5数组是:
text
[10 20 30]数字是:
text
5NumPy 相当于把 5 看成:
text
[5 5 5]然后进行:
text
[10 20 30]
+
[ 5 5 5]
-----------
[15 25 35]这个过程就是广播。
32.2.1 一个数字广播到整个数组
例如:
python
prices = np.array([10, 20, 30, 40])
prices * 1.1相当于:
text
[10 20 30 40]
×
[1.1 1.1 1.1 1.1]得到:
text
[11. 22. 33. 44.]这在数据处理中非常常见。
32.2.2 两个数组也可以广播
例如:
python
scores = np.array([
[80, 90, 70],
[60, 75, 85],
[90, 95, 100],
])每一列代表:
text
数学 英语 Python现在我们希望给每一列加上不同的权重:
python
weights = np.array([0.3, 0.3, 0.4])直接:
python
scores * weightsNumPy 会进行广播:
text
[80 90 70] [0.3 0.3 0.4]
[60 75 85] × [0.3 0.3 0.4]
[90 95 100] [0.3 0.3 0.4]结果:
text
[
[24. 27. 28.],
[18. 22.5 34.],
[27. 28.5 40.]
]你不需要写三层循环。
32.2.3 广播的核心规则
不要死记广播规则。
先记住一个非常实用的直觉:
NumPy 会尝试把形状较小的数组“扩展”到可以进行运算的形状。
例如:
python
a.shapetext
(3, 3)而:
python
b.shapetext
(3,)NumPy 可以把 b 广播成:
text
(3, 3)所以:
python
a + b是合法的。
但是:
python
a = np.zeros((3, 3))
b = np.zeros((2,))这时候:
python
a + b就不行。
因为:
text
(3, 3)
( 2)最后一维 3 和 2 对不上。
32.3 聚合
到目前为止,我们主要是在:
数组 → 数组
例如:
python
numbers * 2得到一个新的数组。
但很多时候我们想做的是:
数组 → 一个值
例如:
text
一组考试成绩
↓
平均成绩这就是聚合(Aggregation)。
最常见的聚合操作:
python
sum()
mean()
max()
min()32.4 sum
例如:
python
numbers = np.array([10, 20, 30, 40])
numbers.sum()得到:
text
100也可以写:
python
np.sum(numbers)两者通常都可以。
32.4.1 为什么推荐 .sum()?
如果你已经有一个 NumPy 数组:
python
numbers那么:
python
numbers.sum()非常自然。
它表达的是:
“这个数组求和。”
而:
python
sum(numbers)是 Python 内置函数。
NumPy 中更推荐:
python
numbers.sum()因为 NumPy 可以针对自己的数组结构进行优化。
32.5 mean
mean 就是平均值。
python
scores = np.array([80, 90, 70, 100])
scores.mean()得到:
text
85.0也可以:
python
np.mean(scores)32.5.1 不要自己写平均值
当然你可以:
python
scores.sum() / len(scores)但 NumPy 已经提供:
python
scores.mean()所以直接使用它。
32.6 max
找最大值:
python
numbers = np.array([10, 50, 20, 90, 30])
numbers.max()结果:
text
90也可以:
python
np.max(numbers)32.7 min
找最小值:
python
numbers.min()得到:
text
10所以:
python
numbers.min()
numbers.max()
numbers.mean()
numbers.sum()这几个方法应该非常熟悉。
32.7.1 二维数组怎么办?
真正有意思的是二维数组。
例如:
python
scores = np.array([
[80, 90, 70],
[60, 75, 85],
[90, 95, 100],
])可以理解成:
text
学生 × 科目那么:
python
scores.sum()会把所有元素加起来:
text
745但是我们经常想:
每个学生的总成绩是多少?
这时候就需要:
python
scores.sum(axis=1)得到:
text
[240 220 285]32.7.2 axis 是什么?
axis 一开始确实有点反直觉。
最简单的理解方式是:
对于:
python
scores.shapetext
(3, 3)我们有两个方向:
text
axis=0
↓
沿着行往下看
axis=1
→
沿着列往右看所以:
python
scores.sum(axis=1)就是:
每一行分别求和。
得到:
text
[240 220 285]而:
python
scores.sum(axis=0)就是:
每一列分别求和。
得到:
text
[230 260 255]可以把它记成:
text
axis=0 → 压掉第 0 个维度
axis=1 → 压掉第 1 个维度这个理解比死记“axis=0 是列,axis=1 是行”更可靠。
32.8 矩阵
现在进入一个非常重要的部分:
矩阵。
NumPy 的二维数组:
python
matrix = np.array([
[1, 2],
[3, 4],
])可以看成一个矩阵:
text
┌ ┐
│ 1 2 │
│ 3 4 │
└ ┘它的 shape:
python
matrix.shape是:
text
(2, 2)32.8.1 矩阵加法
两个矩阵:
python
a = np.array([
[1, 2],
[3, 4],
])
b = np.array([
[10, 20],
[30, 40],
])可以:
python
a + b结果:
text
[
[11 22],
[33 44]
]还是逐元素运算。
32.8.2 * 不是矩阵乘法
这是 NumPy 初学者最容易踩的坑之一。
python
a * b结果:
text
[
[10 40],
[90 160]
]它做的是:
text
1×10 2×20
3×30 4×40不是我们在线性代数中学到的矩阵乘法。
32.8.3 矩阵乘法
矩阵乘法使用:
python
@例如:
python
a @ b结果:
text
[
[70 100],
[150 220]
]为什么?
第一行第一列:
text
1×10 + 2×30
= 70第一行第二列:
text
1×20 + 2×40
= 100所以:
python
a @ b才是矩阵乘法。
32.9 线性代数基础
你不需要为了学习 NumPy 重新学一遍大学线性代数。
先理解几个核心概念就够了。
32.9.1 向量
例如:
python
v = np.array([1, 2, 3])可以把它看成一个向量:
text
v = [1, 2, 3]它可以表示:
text
位置
速度
颜色
特征
坐标具体含义取决于你的数据。
32.9.2 向量加法
python
a = np.array([1, 2])
b = np.array([3, 4])
a + b结果:
text
[4 6]几何上可以理解成:
text
向量 + 向量
↓
得到新的向量32.9.3 点积
两个向量:
python
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])可以计算点积:
python
a @ b结果:
text
32因为:
text
1×4 + 2×5 + 3×6
= 4 + 10 + 18
= 32也可以使用:
python
np.dot(a, b)32.9.4 转置
矩阵:
python
a = np.array([
[1, 2, 3],
[4, 5, 6],
])shape:
text
(2, 3)转置:
python
a.T得到:
text
[
[1, 4],
[2, 5],
[3, 6]
]shape 变成:
text
(3, 2)也就是:
text
(2, 3)
↓ transpose
(3, 2)转置在矩阵计算、机器学习、数据处理里面非常常见。
32.9.5 矩阵乘法为什么重要?
假设:
text
输入数据
↓
矩阵
↓
权重矩阵
↓
新的矩阵大量机器学习计算,本质上就是在进行各种:
text
矩阵 × 矩阵或者:
text
矩阵 × 向量所以:
python
@这个运算符值得记住。
32.10 NumPy 与 JS Array 对比
如果你有 JavaScript 基础,这部分非常重要。
JavaScript:
javascript
const numbers = [1, 2, 3];Python:
python
numbers = [1, 2, 3]NumPy:
python
numbers = np.array([1, 2, 3])它们看起来很像,但设计目标完全不同。
32.10.1 加法
JavaScript:
javascript
[1, 2, 3] + [4, 5, 6]不是数学意义上的数组加法。
而 NumPy:
python
np.array([1, 2, 3]) + np.array([4, 5, 6])得到:
text
[5 7 9]32.10.2 乘法
JavaScript:
javascript
[1, 2, 3] * 2不会得到:
text
[2, 4, 6]通常需要:
javascript
const numbers = [1, 2, 3];
numbers.map(x => x * 2);NumPy:
python
numbers = np.array([1, 2, 3])
numbers * 2直接得到:
text
[2 4 6]32.10.3 map
JavaScript:
javascript
const result = numbers.map(x => x * 2);NumPy:
python
result = numbers * 2NumPy 不只是把 map 写得更短。
它的核心思想是:
向量化(Vectorization)。
也就是说,我们告诉 NumPy:
text
“整个数组乘 2”而不是:
text
“第一个元素乘 2,
第二个元素乘 2,
第三个元素乘 2……”32.10.4 reduce
JavaScript:
javascript
const total = numbers.reduce(
(sum, x) => sum + x,
0
);NumPy:
python
total = numbers.sum()JavaScript:
javascript
Math.max(...numbers)NumPy:
python
numbers.max()JavaScript:
javascript
Math.min(...numbers)NumPy:
python
numbers.min()JavaScript:
javascript
numbers.reduce((sum, x) => sum + x, 0) / numbers.lengthNumPy:
python
numbers.mean()32.10.5 一个重要区别:NumPy Array 不是 JS Array
不要把:
python
np.array(...)简单理解成:
javascript
Array它们解决的问题不一样。
JavaScript Array 更像:
一个通用的动态容器。
可以放:
javascript
[1, "hello", true, {}, null]NumPy ndarray 更像:
一块结构规则、类型统一、适合数学计算的数据。
例如:
python
np.array([1, 2, 3, 4])它知道:
text
shape
dtype
维度
内存布局因此 NumPy 可以进行大量高效的数值计算。
32.10.6 JS Array 与 NumPy ndarray 对照表
| 操作 | JavaScript | NumPy |
|---|---|---|
| 创建数组 | [] | np.array() |
| 长度 | .length | .size |
| 形状 | 没有直接对应 | .shape |
| 类型 | 动态 | .dtype |
| map | .map() | 向量化运算 |
| filter | .filter() | 布尔索引 |
| reduce 求和 | .reduce() | .sum() |
| 最大值 | Math.max() | .max() |
| 最小值 | Math.min() | .min() |
| 平均值 | 手动计算 | .mean() |
| 数组加法 | 需手动处理 | a + b |
| 数组乘法 | 需 .map() | a * b |
| 矩阵乘法 | 需要自己实现/库 | a @ b |
| 转置 | 无原生对应 | .T |
32.11 把这些操作放在一起
现在我们做一个小例子。
假设这是三个人三门课的成绩:
python
import numpy as np
scores = np.array([
[80, 90, 70],
[60, 75, 85],
[90, 95, 100],
])所有成绩总和
python
scores.sum()text
745所有成绩平均值
python
scores.mean()text
82.777...每个人的总分
python
scores.sum(axis=1)text
[240 220 285]每门课的平均分
python
scores.mean(axis=0)得到:
text
[76.666... 86.666... 85.]每个人最高分
python
scores.max(axis=1)text
[90 85 100]每个人最低分
python
scores.min(axis=1)text
[70 60 90]所有成绩加 5 分
python
scores + 5NumPy 自动广播:
text
[
[85, 95, 75],
[65, 80, 90],
[95, 100, 105]
]32.12 NumPy 真正的思维方式
到这里,你应该开始改变一个习惯。
以前写 Python:
python
result = []
for number in numbers:
result.append(number * 2)现在 NumPy:
python
result = numbers * 2以前:
python
total = 0
for number in numbers:
total += number现在:
python
total = numbers.sum()以前:
python
average = sum(numbers) / len(numbers)现在:
python
average = numbers.mean()以前:
python
maximum = max(numbers)现在:
python
maximum = numbers.max()这不是简单的“代码少写几行”。
真正的变化是:
text
Python 思维
一个元素
↓
处理
↓
下一个元素
↓
处理
↓
...变成:
text
NumPy 思维
整个数组
↓
一次操作
↓
得到结果这就是向量化思维。
32.13 一个非常重要的经验
如果你发现自己在 NumPy 中写了很多这样的代码:
python
for row in data:
for value in row:
...先别急着继续写。
停下来问自己:
这个操作能不能直接作用于整个数组?
例如:
python
for x in numbers:
x * 2很可能可以:
python
numbers * 2再比如:
python
total = 0
for x in numbers:
total += x直接:
python
numbers.sum()再比如:
python
maximum = numbers[0]
for x in numbers:
if x > maximum:
maximum = x直接:
python
numbers.max()32.14 本章应该真正掌握什么?
这一章不要把重点放在背 API。
真正应该建立的是下面这张图:
text
NumPy ndarray
│
┌────────────┼────────────┐
↓ ↓ ↓
运算 聚合 线性代数
│ │ │
+ - * / sum vector
│ mean matrix
↓ max │
广播 min @
│ │
└──────────────┬────────────┘
↓
向量化计算最重要的几个操作:
python
a + b
a - b
a * b
a / b
a + 10
a * 10
a.sum()
a.mean()
a.max()
a.min()
a.sum(axis=0)
a.sum(axis=1)
a.T
a @ b如果这些东西你已经能够自然地写出来,那么 NumPy 的核心计算模型就已经入门了。
32.15 一个小练习
最后不要只是看。
自己创建:
python
temperatures = np.array([
[20, 22, 25, 23],
[18, 21, 24, 22],
[19, 23, 26, 24],
])尝试回答:
① 所有温度的平均值是多少?
python
temperatures.mean()② 每一天的平均温度是多少?
python
temperatures.mean(axis=0)③ 每个城市的平均温度是多少?
python
temperatures.mean(axis=1)④ 每个城市的最高温度是多少?
python
temperatures.max(axis=1)⑤ 所有温度增加 2 度?
python
temperatures + 2注意这里的 + 2 就是广播。
最后记住一句话
如果说 Python 的核心思想之一是:
“把问题拆成一步一步的操作。”
那么 NumPy 的核心思想更接近:
“不要想着怎么遍历每个元素,先想整个数组应该进行什么计算。”
这就是从 Python 进入科学计算世界时,一个非常重要的思维转变。
而下一步,当我们把 NumPy 的这种数组计算思想带入真实数据,就会自然遇到一个更强大的工具:Pandas。