读书报告
读书报告
- NumPy基本函数与示例
NumPy是Python中用于科学计算的基础库,提供了高性能的多维数组对象及相关工具。
基本函数用法
import numpy as np
创建数组
arr1 = np.array([1, 2, 3]) # 一维数组
arr2 = np.zeros((3, 3)) # 3x3零矩阵
arr3 = np.arange(0, 10, 2) # 0到10,步长为2
数组运算
arr4 = arr1 + 5 # 广播机制
arr5 = np.dot(arr1, arr1) # 点积
统计函数
mean = np.mean(arr1) # 平均值
std = np.std(arr1) # 标准差
具体问题求解:解线性方程组
# 解方程组:
# 3x + y = 9
# x + 2y = 8
A = np.array([[3, 1], [1, 2]])
b = np.array([9, 8])
x = np.linalg.solve(A, b) # 解为 [2., 3.]
- SciPy基本函数与示例
SciPy建立在NumPy基础上,提供了更多科学计算功能。
基本函数用法
from scipy import optimize, integrate, stats
优化
result = optimize.minimize(lambda x: x**2 + 5, x0=2)
积分
area = integrate.quad(lambda x: x**2, 0, 4) # 0到4积分x^2
统计
rv = stats.norm(loc=0, scale=1) # 标准正态分布
prob = rv.cdf(1.96) # P(X ≤ 1.96)
具体问题求解:曲线拟合
拟合数据点到二次函数
x = np.array([0, 1, 2, 3, 4])
y = np.array([1, 1.5, 3, 4.5, 7])
def quadratic(x, a, b, c):
return a*x**2 + b*x + c
params, _ = optimize.curve_fit(quadratic, x, y)
最佳拟合参数为 [0.45, 0.65, 0.85]
- Pandas基本函数与示例
Pandas提供了高效的数据结构和数据分析工具。
基本函数用法
import pandas as pd
创建DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Salary': [50000, 60000, 70000]}
df = pd.DataFrame(data)
数据操作
df_filtered = df[df['Age'] > 28] # 筛选
df_sorted = df.sort_values(by='Salary') # 排序
mean_salary = df['Salary'].mean() # 平均薪资
具体问题求解:数据清洗与分析
处理缺失值
df_with_nan = pd.DataFrame({'A': [1, 2, np.nan], 'B': [5, np.nan, np.nan]})
df_cleaned = df_with_nan.dropna() # 删除含NaN的行
df_filled = df_with_nan.fillna(value=0) # 用0填充NaN
分组统计
df.groupby('Name')['Salary'].agg(['mean', 'max', 'min'])
- Matplotlib基本函数与示例
Matplotlib是Python的主要绘图库。
基本函数用法
import matplotlib.pyplot as plt
# 线图
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title('Sine Wave')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.show()
# 散点图
plt.scatter(x, y, color='red', marker='o')
plt.show()
图像处理示例
from scipy import misc
from scipy.ndimage import filters
# 读取图像
face = misc.face(gray=True)
# 图像滤波
blurred_face = filters.gaussian_filter(face, sigma=5)
# 显示图像
plt.figure(figsize=(10, 5))
plt.subplot(121)
plt.imshow(face, cmap='gray')
plt.title('Original')
plt.subplot(122)
plt.imshow(blurred_face, cmap='gray')
plt.title('Blurred')
plt.show()
综合应用示例
# 生成随机数据并分析
np.random.seed(42)
data = pd.DataFrame({
'Height': np.random.normal(170, 10, 100),
'Weight': np.random.normal(70, 5, 100),
'Gender': np.random.choice(['M', 'F'], 100)
})
# 统计分析
print(data.describe())
# 分组统计
print(data.groupby('Gender').agg(['mean', 'std']))
# 可视化
plt.figure(figsize=(12, 5))
plt.subplot(131)
plt.hist(data['Height'], bins=15)
plt.title('Height Distribution')
plt.subplot(132)
plt.scatter(data['Height'], data['Weight'])
plt.xlabel('Height')
plt.ylabel('Weight')
plt.subplot(133)
data.boxplot(column='Weight', by='Gender')
plt.suptitle('')
plt.show()
这四个库构成了Python科学计算的核心生态系统:
- NumPy提供基础数组操作
- SciPy扩展科学计算功能
- Pandas专注于数据处理和分析
- Matplotlib实现数据可视化
它们相互配合,能够高效解决从基础数学运算到复杂数据分析的各种问题。
浙公网安备 33010602011771号