数组变形与操作
学习目标
- 掌握 reshape、flatten、ravel 等变形操作
- 学会数组的拼接(concatenate、stack、hstack、vstack)
- 学会数组的分割(split、hsplit、vsplit)
- 理解转置和轴交换
reshape:改变形状
reshape 是最常用的变形操作——在不改变数据的前提下改变数组的形状。
基本用法
import numpy as np
arr = np.arange(12) # [ 0 1 2 3 4 5 6 7 8 9 10 11]
print(arr.shape) # (12,)
# 变成 3 行 4 列
m1 = arr.reshape(3, 4)
print(m1)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
# 变成 4 行 3 列
m2 = arr.reshape(4, 3)
print(m2)
# [[ 0 1 2]
# [ 3 4 5]
# [ 6 7 8]
# [ 9 10 11]]
# 变成 2×2×3 的三维数组
m3 = arr.reshape(2, 2, 3)
print(m3)
# [[[ 0 1 2]
# [ 3 4 5]]
# [[ 6 7 8]
# [ 9 10 11]]]
元素总数必须一致
reshape 前后的元素总数必须相同,否则报错:
arr = np.arange(12) # 12 个元素
arr.reshape(3, 5) # ❌ 报错!3 × 5 = 15 ≠ 12
arr.reshape(3, 4) # ✅ 3 × 4 = 12
用 -1 自动计算
-1 表示"让 NumPy 自动计算这个维度":
arr = np.arange(12)
# 我想要 3 行,列数你帮我算
m1 = arr.reshape(3, -1) # 自动算出 4 列
print(m1.shape) # (3, 4)
# 我想要 4 列,行数你帮我算
m2 = arr.reshape(-1, 4) # 自动算出 3 行
print(m2.shape) # (3, 4)
# 变成一列(列向量)
col = arr.reshape(-1, 1)
print(col.shape) # (12, 1)
-1 只能用一次
reshape 中最多只有一个维度可以是 -1。因为只有一个未知数才能算出来。
arr.reshape(-1, -1) # ❌ 报错!不能有两个 -1