Python科学计算库读书报告
NumPy、SciPy、Pandas和Matplotlib的读书报告
一、NumPy基础与应用
基本函数用法
NumPy是Python中用于科学计算的基础库,提供了高性能的多维数组对象和工具。
import numpy as np
创建数组
arr1 = np.array([1, 2, 3, 4, 5]) # 一维数组
arr2 = np.array([[1, 2, 3], [4, 5, 6]]) # 二维数组
zeros_arr = np.zeros((3, 3)) # 3x3零矩阵
ones_arr = np.ones((2, 4)) # 2x4全1矩阵
random_arr = np.random.rand(5) # 随机数组
数组运算
arr = np.array([1, 2, 3, 4])
print(arr + 2) # 每个元素加2
print(arr * 3) # 每个元素乘3
print(np.sqrt(arr)) # 平方根
print(np.exp(arr)) # 指数
数组索引和切片
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr[1, 2]) # 第2行第3列
print(arr[:, 1]) # 所有行的第2列
print(arr[0:2, 1:3]) # 子矩阵
统计函数
print(np.mean(arr)) # 平均值
print(np.median(arr)) # 中位数
print(np.std(arr)) # 标准差
print(np.sum(arr)) # 总和
实际问题解决:求解线性方程组
解方程组:
2x + y = 8
- y = 1
= np.array([[2, 1], [1, -1]])
= np.array([8, 1])
= np.linalg.solve(A, b)
print(f"解为: x = {x[0]}, y = {x[1]}")
二、SciPy基础与应用
基本函数用法
SciPy建立在NumPy基础上,提供了更多科学计算工具。
from scipy import linalg, optimize, interpolate, stats
线性代数
= np.array([[1, 2], [3, 4]])
print(linalg.det(A)) # 行列式
print(linalg.inv(A)) # 逆矩阵
优化
def f(x):
return x2 + 10*np.sin(x)
result = optimize.minimize(f, x0=0)
print(f"最小值在x={result.x}, f(x)={result.fun}")
插值
= np.linspace(0, 10, 10)
= np.sin(x)
= interpolate.interp1d(x, y, kind='cubic')
x_new = np.linspace(0, 10, 100)
y_new = f(x_new)
统计
data = np.random.normal(size=1000)
print(stats.describe(data)) # 描述统计
实际问题解决:曲线拟合
拟合数据点到二次函数
= np.array([0, 1, 2, 3, 4, 5])
= np.array([0.1, 0.9, 4.1, 8.9, 16.1, 25.1])
def func(x, a, b, c):
return ax2 + bx + c
popt, pcov = optimize.curve_fit(func, x, y)
print(f"拟合参数: a={popt[0]}, b={popt[1]}, c={popt[2]}")
三、Pandas基础与应用
基本函数用法
Pandas提供了高效的数据结构和数据分析工具。
import pandas as pd
创建DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Salary': [50000, 60000, 70000]}
df = pd.DataFrame(data)
基本操作
print(df.head()) # 查看前几行
print(df.describe()) # 描述统计
print(df['Age'].mean()) # 计算平均年龄
数据筛选
print(df[df['Age'] > 28]) # 筛选年龄大于28的记录
print(df[(df['Age'] > 25) & (df['Salary'] < 65000)]) # 复合条件筛选
数据分组和聚合
grouped = df.groupby('Age')
print(grouped.mean()) # 按年龄分组计算平均值
处理缺失值
df.loc[1, 'Salary'] = np.nan
print(df.fillna(0)) # 用0填充缺失值
实际问题解决:数据分析
读取CSV文件并分析
假设有学生成绩数据:姓名,数学,物理,化学
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Math': [85, 78, 92, 64, 88],
'Physics': [90, 82, 95, 70, 85],
'Chemistry': [88, 76, 90, 68, 82]
df = pd.DataFrame(data)
计算总分和平均分
df['Total'] = df['Math'] + df['Physics'] + df['Chemistry']
df['Average'] = df['Total'] / 3
找出平均分最高的学生
top_student = df.loc[df['Average'].idxmax()]
print(f"最高分学生: {top_student['Name']}, 平均分: {top_student['Average']:.2f}")
各科平均分
print(f"数学平均分: {df['Math'].mean():.2f}")
print(f"物理平均分: {df['Physics'].mean():.2f}")
print(f"化学平均分: {df['Chemistry'].mean():.2f}")
四、Matplotlib基础与应用
基本函数用法
Matplotlib是Python的主要绘图库。
import matplotlib.pyplot as plt
基本绘图
= np.linspace(0, 10, 100)
= np.sin(x)
plt.figure(figsize=(8, 4))
plt.plot(x, y, label='sin(x)', color='blue', linestyle='-')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Sine Function')
plt.legend()
plt.grid(True)
plt.show()
多子图
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot(x, np.sin(x), 'r-')
plt.title('Sine')
plt.subplot(1, 2, 2)
plt.plot(x, np.cos(x), 'b--')
plt.title('Cosine')
plt.tight_layout()
plt.show()
柱状图
labels = ['A', 'B', 'C', 'D']
values = [10, 25, 45, 30]
plt.bar(labels, values)
plt.title('Bar Chart')
plt.show()
散点图
= np.random.rand(50)
= np.random.rand(50)
colors = np.random.rand(50)
sizes = 1000 * np.random.rand(50)
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5)
plt.title('Scatter Plot')
plt.show()
实际问题解决:图像处理与可视化
from scipy import misc
from scipy.ndimage import filters
图像处理
face = misc.face(gray=True) # 加载示例图像
plt.figure(figsize=(10, 5))
plt.subplot(1, 3, 1)
plt.imshow(face, cmap=plt.cm.gray)
plt.title('Original Image')
plt.axis('off')
高斯模糊
blurred_face = filters.gaussian_filter(face, sigma=3)
plt.subplot(1, 3, 2)
plt.imshow(blurred_face, cmap=plt.cm.gray)
plt.title('Blurred Image')
plt.axis('off')
边缘检测
edge_face = filters.sobel(face)
plt.subplot(1, 3, 3)
plt.imshow(edge_face, cmap=plt.cm.gray)
plt.title('Edge Detection')
plt.axis('off')
plt.tight_layout()
plt.show()
数据可视化示例:绘制股票价格走势
dates = pd.date_range('20230101', periods=100)
prices = 100 + np.cumsum(np.random.randn(100))
df_stock = pd.DataFrame({'Price': prices}, index=dates)
plt.figure(figsize=(10, 5))
plt.plot(df_stock.index, df_stock['Price'], 'b-', label='Price')
plt.fill_between(df_stock.index, df_stock['Price'],
df_stock['Price'].min(), color='blue', alpha=0.1)
plt.title('Stock Price Trend')
plt.xlabel('Date')
plt.ylabel('Price')
plt.grid(True)
plt.legend()
plt.show()
综合应用案例
案例:分析鸢尾花数据集
from sklearn.datasets import load_iris
加载数据
iris = load_iris()
iris_df = pd.DataFrame(iris.data, columns=iris.feature_names)
iris_df['species'] = iris.target_names[iris.target]
基本统计
print(iris_df.groupby('species').describe())
可视化
plt.figure(figsize=(12, 8))
for i, species in enumerate(iris.target_names):
plt.subplot(2, 2, i+1)
species_data = iris_df[iris_df['species'] == species]
plt.scatter(species_data['sepal length (cm)'],
species_data['sepal width (cm)'])
plt.title(species)
plt.xlabel('Sepal Length')
plt.ylabel('Sepal Width')
plt.tight_layout()
plt.show()
箱线图比较
plt.figure(figsize=(10, 6))
iris_df.boxplot(column='petal length (cm)', by='species')
plt.title('Petal Length by Species')
plt.suptitle('') # 移除自动标题
plt.show()
案例:求解微分方程
from scipy.integrate import odeint
定义微分方程:dy/dt = -ky
def model(y, t, k):
dydt = -k * y
return dydt
初始条件
y0 = 5
时间点
= np.linspace(0, 20, 100)
求解
= 0.3
= odeint(model, y0, t, args=(k,))
可视化
plt.figure(figsize=(8, 5))
plt.plot(t, y, 'b-', label='y(t)')
plt.xlabel('Time')
plt.ylabel('y')
plt.title('Solution of dy/dt = -ky')
plt.legend()
plt.grid(True)
plt.show()
总结
本报告介绍了Python中四个核心科学计算库的基本用法和实际应用:
NumPy:提供了高效的多维数组操作和数学函数,是科学计算的基础。
SciPy:在NumPy基础上扩展,提供了更多高级科学计算工具,如优化、积分、插值等。
Pandas:提供了强大的数据结构和数据分析工具,特别适合处理表格数据。
Matplotlib:是Python的主要绘图库,可以创建各种高质量的图表和可视化。
通过这些库的组合使用,我们可以高效地解决各种科学计算和数据分析问题,从简单的数学计算到复杂的数据分析和可视化任务。