Python科学计算库读书报告
1. NumPy、SciPy、Pandas、Matplotlib基本函数用法
1.1 NumPy基本函数
import numpy as np # 创建数组 arr1 = np.array([1, 2, 3, 4, 5]) # 一维数组 arr2 = np.array([[1, 2, 3], [4, 5, 6]]) # 二维数组 zeros = np.zeros((3, 3)) # 3x3零矩阵 ones = np.ones((2, 4)) # 2x4全1矩阵 random_arr = np.random.rand(5) # 随机数组 # 数组运算 sum_arr = arr1 + arr2[0] # 数组加法 dot_product = np.dot(arr1, arr2[0]) # 点积 matrix_mult = np.matmul(arr2, arr2.T) # 矩阵乘法 # 统计函数 mean_val = np.mean(arr1) # 平均值 std_val = np.std(arr1) # 标准差 max_val = np.max(arr2) # 最大值
1.2 SciPy基本函数
from scipy import linalg, optimize, stats # 线性代数 A = np.array([[1, 2], [3, 4]]) b = np.array([5, 6]) x = linalg.solve(A, b) # 解线性方程组 det_A = linalg.det(A) # 行列式 # 优化 def f(x): return (x[0] - 1)**2 + (x[1] - 2.5)**2 result = optimize.minimize(f, [0, 0]) # 最小化函数 # 统计 normal_dist = stats.norm(loc=0, scale=1) # 正态分布 p_value = stats.ttest_ind(np.random.randn(100), np.random.randn(100)).pvalue # t检验
1.3 Pandas基本函数
import pandas as pd # 创建DataFrame data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ['NY', 'LA', 'Chicago']} df = pd.DataFrame(data) # 数据操作 filtered = df[df['Age'] > 28] # 过滤 grouped = df.groupby('City').mean() # 分组聚合 sorted_df = df.sort_values('Age', ascending=False) # 排序 # 处理缺失值 df_with_nan = df.copy() df_with_nan.loc[1, 'Age'] = np.nan cleaned = df_with_nan.dropna() # 删除缺失值 filled = df_with_nan.fillna(0) # 填充缺失值
1.4 Matplotlib基本函数
import matplotlib.pyplot as plt # 折线图 x = np.linspace(0, 10, 100) y = np.sin(x) plt.figure(figsize=(8, 4)) plt.plot(x, y, label='sin(x)') plt.title('Sine Wave') plt.xlabel('x') plt.ylabel('sin(x)') plt.legend() plt.grid() plt.show() # 散点图 x = np.random.randn(100) y = x + np.random.randn(100) * 0.5 plt.scatter(x, y, alpha=0.6) plt.title('Scatter Plot') plt.show() # 直方图 data = np.random.randn(1000) plt.hist(data, bins=30, density=True, alpha=0.6, color='g') plt.title('Histogram') plt.show()
2. 具体问题求解示例
2.1 线性方程组求解(NumPy/SciPy)
# 解方程组: # 3x + y = 9 # x + 2y = 8 A = np.array([[3, 1], [1, 2]]) b = np.array([9, 8]) x = np.linalg.solve(A, b) print(f"解为: x = {x[0]:.2f}, y = {x[1]:.2f}")
2.2 数据清洗与分析(Pandas)
# 分析学生成绩数据集 data = { 'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'], 'Math': [90, 85, np.nan, 78, 92], 'English': [88, 92, 85, 80, np.nan], 'Science': [95, 88, 90, 85, 93] } df = pd.DataFrame(data) # 填充缺失值 df_filled = df.fillna(df.mean()) # 计算总分和平均分 df_filled['Total'] = df_filled[['Math', 'English', 'Science']].sum(axis=1) df_filled['Average'] = df_filled[['Math', 'English', 'Science']].mean(axis=1) print(df_filled.sort_values('Average', ascending=False))
2.3 函数最小化(SciPy)
# 最小化函数 f(x) = (x-3)^2 + (y-5)^2 def f(params): x, y = params return (x-3)**2 + (y-5)**2 result = optimize.minimize(f, [0, 0]) print(f"最小值在 x={result.x[0]:.2f}, y={result.x[1]:.2f}")
3. 图像处理示例
3.1 图像加载与显示
from scipy import misc from scipy.ndimage import filters # 加载示例图像 face = misc.face(gray=True) plt.figure(figsize=(10, 5)) plt.subplot(1, 2, 1) plt.imshow(face, cmap='gray') plt.title('原始图像') # 应用高斯滤波 blurred = filters.gaussian_filter(face, sigma=5) plt.subplot(1, 2, 2) plt.imshow(blurred, cmap='gray') plt.title('高斯滤波后') plt.show()
3.2 边缘检测
from skimage import filters # 边缘检测 edges = filters.sobel(face) plt.figure(figsize=(10, 5)) plt.subplot(1, 2, 1) plt.imshow(face, cmap='gray') plt.title('原始图像') plt.subplot(1, 2, 2) plt.imshow(edges, cmap='gray') plt.title('边缘检测') plt.show()
总结
本报告涵盖了NumPy、SciPy、Pandas和Matplotlib四个Python科学计算库的基本用法,包括:
-
数组操作、线性代数、统计计算等基本功能
-
实际问题的求解示例,如线性方程组、数据分析和函数优化
-
图像处理的基本技术,包括滤波、边缘检测和直方图均衡化
这些库共同构成了Python科学计算的基础,能够高效处理数值计算、数据分析和可视化任务。通过掌握这些工具,可以解决科学研究和工程实践中的各种计算问题。

浙公网安备 33010602011771号