📌 目录
- NumPy 数组是 SciPy 的基础
- ndarray 是什么?
- 如何用 NumPy 创建数组?
- SciPy 如何使用 NumPy 数组?
- 共享内存:SciPy 模块的输入输出
- 示例:SciPy 与 NumPy 协作计算
- 出站链接与参考资料
1. NumPy 数组是 SciPy 的基础
SciPy 库中大多数函数的输入和输出都是 NumPy 的多维数组对象(ndarray)。这意味着:
- 学好 NumPy = 用好 SciPy 的前提;
- SciPy 并不会自己创建数据结构,而是直接基于 NumPy 运算。
📌 简单来说,NumPy 是底层引擎,SciPy 是高级工具箱。
2. ndarray
是什么?
ndarray
是 NumPy 提供的核心数据结构(n-dimensional array):
- 表示任意维度的数值表格;
- 支持向量化操作(比 for 循环快得多);
- SciPy 函数接收的几乎都是 ndarray 类型数据。
3. 如何用 NumPy 创建数组?
一维数组
import numpy as np
a = np.array([1, 2, 3])
print(a) # 输出:[1 2 3]
二维数组
b = np.array([[1, 2], [3, 4]])
print(b)
# 输出:
# [[1 2]
# [3 4]]
创建全 0 / 全 1 的数组
np.zeros((2, 3)) # 2行3列的全0数组
np.ones((3, 3)) # 3x3 全1矩阵
4. SciPy 如何使用 NumPy 数组?
我们来看一个 SciPy 函数处理 NumPy 数组的例子。
from scipy import linalg
import numpy as np
# 创建 2x2 矩阵
A = np.array([[3, 2], [1, 4]])
# 求解矩阵的逆
inv_A = linalg.inv(A)
print("逆矩阵:\n", inv_A)
🧠 注意:SciPy 函数并没有构造新类型,而是接收 NumPy 的数组,并输出 NumPy 数组结果。
5. 共享内存:SciPy 模块的输入输出
SciPy 中的模块并不会改变输入数组,而是返回新的数组对象。
例如:
import numpy as np
from scipy import signal
x = np.array([1, 2, 3, 4])
y = signal.detrend(x) # 去线性趋势
print(y)
✅ 输入 x
保持不变,输出为新的数组 y
,这种方式确保数据可控、可追踪。
6. 示例:SciPy 与 NumPy 协作计算
我们用 NumPy 创建一组点,用 SciPy 对其插值(使用 scipy.interpolate.interp1d
):
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
# 原始数据点
x = np.linspace(0, 10, 10)
y = np.sin(x)
# 创建插值函数
f = interp1d(x, y, kind='cubic')
# 生成更密集的新点
xnew = np.linspace(0, 10, 100)
ynew = f(xnew)
# 绘图展示
plt.plot(x, y, 'o', label='原始点')
plt.plot(xnew, ynew, '-', label='插值曲线')
plt.legend()
plt.show()
这就是典型的 NumPy + SciPy + Matplotlib 联合作战范式。
🔗 出站链接与参考资料
📘 官方文档
- NumPy 官网:
https://numpy.org/ - SciPy 官网:
https://scipy.org/ - SciPy 插值模块官方 API:
https://docs.scipy.org/doc/scipy/reference/interpolate.html
🎓 学习资源
- NumPy 教程(官方英文):
https://numpy.org/doc/stable/user/quickstart.html - 《Python 科学计算生态系统概览》:
https://scipy-lectures.org/
发表回复