python常用科学计算库及使用示例
一、NumPy - 数值计算基础库
安装
pip install numpy核心功能示例
1. 数组创建与运算
import numpy as np# 创建数组
arr = np.array([1, 2, 3, 4])
matrix = np.array([[1, 2], [3, 4]])# 数学运算
print(arr + 1)        # [2 3 4 5]
print(matrix @ matrix) # 矩阵乘法 [[7 10] [15 22]]# 统计函数
data = np.array([1, 2, 3, 4, 5])
print(np.mean(data))   # 3.0
print(np.std(data))    # 1.41421356237309512. 随机数与线性代数
# 随机数
rand_arr = np.random.rand(3, 3)  # 3x3随机矩阵# 线性代数
A = np.array([[1, 2], [3, 4]])
inv_A = np.linalg.inv(A)  # 逆矩阵
eigvals = np.linalg.eigvals(A)  # 特征值二、SciPy - 科学计算工具箱
安装
pip install scipy核心功能示例
1. 积分与优化
from scipy import integrate, optimize# 定积分
def f(x):return x**2
result, _ = integrate.quad(f, 0, 1)  # 0.333...# 函数最小值
result = optimize.minimize(lambda x: (x-3)**2, x0=0)
print(result.x)  # [3.]2. 信号处理与插值
from scipy import signal, interpolate# 生成信号
t = np.linspace(0, 1, 100)
sig = np.sin(2 * np.pi * t)# 滤波
b, a = signal.butter(4, 0.1)  # 4阶低通滤波器
filtered_sig = signal.filtfilt(b, a, sig)# 插值
x = np.linspace(0, 10, 5)
y = np.sin(x)
f = interpolate.interp1d(x, y, kind='cubic')
print(f(5.5))  # 插值结果三、Pandas - 数据分析
安装
pip install pandas核心功能示例
1. 数据结构与操作
import pandas as pd# 创建DataFrame
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)# 基础操作
print(df['Name'])          # 选择列
print(df[df['Age'] > 25])  # 条件筛选
df['Salary'] = [5000, 6000]  # 新增列2. 数据聚合与可视化
# 分组聚合
grouped = df.groupby('Name').mean()  # 按姓名分组求均值# 导出数据
df.to_csv('output.csv', index=False)四、Matplotlib - 数据可视化
安装
pip install matplotlib核心功能示例
1. 基础绘图
import matplotlib.pyplot as pltx = np.linspace(0, 10, 100)
y = np.sin(x)plt.plot(x, y, label='sin(x)')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.legend()
plt.show()2. 高级图表
# 散点图
plt.scatter(x, y, c=y, cmap='viridis')
plt.colorbar()  # 颜色条# 子图
fig, axes = plt.subplots(2, 1)
axes[0].plot(x, y)
axes[1].hist(y, bins=20)
plt.tight_layout()
plt.show()五、Scikit-learn - 机器学习
安装
pip install scikit-learn核心功能示例
1. 分类与回归
from sklearn.linear_model import LinearRegression
from sklearn.datasets import make_regression# 生成数据
X, y = make_regression(n_samples=100, n_features=1)# 训练模型
model = LinearRegression()
model.fit(X, y)# 预测
print(model.predict([[1]]))2. 聚类与降维
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA# K-Means聚类
X = np.random.rand(100, 2)
kmeans = KMeans(n_clusters=3).fit(X)
print(kmeans.labels_)# PCA降维
pca = PCA(n_components=1)
X_reduced = pca.fit_transform(X)六、其他实用库
1. SymPy - 符号计算
from sympy import symbols, diffx = symbols('x')
f = x**2 + 2*x
print(diff(f, x))  # 导数: 2*x + 22. Statsmodels - 统计建模
import statsmodels.api as sm# 线性回归
X = sm.add_constant(X)  # 添加截距项
model = sm.OLS(y, X).fit()
print(model.summary())总结
| 库名 | 核心用途 | 示例场景 | 
|---|---|---|
| NumPy | 数值计算基础 | 数组运算、线性代数 | 
| SciPy | 科学计算扩展 | 积分、优化、信号处理 | 
| Pandas | 数据分析 | 数据清洗、聚合、导出 | 
| Matplotlib | 数据可视化 | 折线图、散点图、子图 | 
| Scikit-learn | 机器学习 | 分类、回归、聚类 | 
| SymPy | 符号计算 | 微积分、方程求解 | 
| Statsmodels | 统计建模 | 回归分析、假设检验 | 
