30天学会Python编程:27.Python数据分析与可视化简介
当前位置:点晴教程→知识管理交流
→『 技术文档交流 』
|
数值计算 | ||
数据处理 | ||
可视化 | ||
机器学习 | ||
科学计算 |
NumPy是Python科学计算的基础库,提供高效的N维数组对象。
import numpy as np
# 创建不同类型的数组
arr1 = np.array([1, 2, 3]) # 一维数组
arr2 = np.zeros((3, 3)) # 3x3零矩阵
arr3 = np.random.rand(100, 4) # 100x4随机数组
arr4 = np.arange(0, 10, 0.1) # 0-10步长0.1的数组
核心要点:
np.array()
从Python列表创建数组np.zeros()和np.ones()
创建特定形状的数组
np.arange()类似Python的range但支持浮点数
np.random模块用于生成随机数据
编程技巧:
dtype
参数控制数组元素的数据类型注意事项:
NumPy的核心优势在于高效的向量化运算:
# 向量化运算示例
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# 基本运算
print("加法:", a + b) # [5 7 9]
print("乘法:", a * b) # [4 10 18]
print("点积:", np.dot(a, b)) # 32
# 广播机制
matrix = np.ones((3, 3))
print("广播加法:\n", matrix + a) # 每行加a
# 通用函数
print("平方根:", np.sqrt(a)) # [1. 1.414 1.732]
print("指数:", np.exp(a)) # [2.718 7.389 20.085]
广播规则:
Pandas的核心数据结构是DataFrame(二维表格)和Series(一维数组)。
import pandas as pd
# 创建DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 28],
'Salary': [50000, 70000, 90000, 62000],
'Department': ['HR', 'IT', 'IT', 'Marketing']
}
df = pd.DataFrame(data)
# 数据筛选
young_high_earners = df[(df['Age'] < 35) & (df['Salary'] > 60000)]
# 分组聚合
department_stats = df.groupby('Department').agg({
'Age': 'mean',
'Salary': ['min', 'max', 'mean']
})
核心功能:
编程技巧:
df.query()
进行复杂条件筛选pd.cut()
进行数据分箱df.apply()
应用自定义函数pd.pivot_table()
创建数据透视表注意事项:
df[df.A>2]['B'] = 5
)copy()
避免视图与副本混淆真实数据常包含不完整或不一致信息:
# 处理缺失值
df.loc[1, 'Age'] = np.nan
df_filled = df.fillna({'Age': df['Age'].median()})
# 重复值处理
df = pd.concat([df, df.iloc[:2]]).drop_duplicates()
# 异常值处理
Q1 = df['Salary'].quantile(0.25)
Q3 = df['Salary'].quantile(0.75)
IQR = Q3 - Q1
df = df[~((df['Salary'] < (Q1 - 1.5 * IQR)) |
(df['Salary'] > (Q3 + 1.5 * IQR)))]
# 类型转换
df['Department'] = df['Department'].astype('category')
df['StartDate'] = pd.to_datetime(df['StartDate'])
Matplotlib是Python最基础的绘图库:
import matplotlib.pyplot as plt
# 创建画布和子图
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
# 折线图
x = np.linspace(0, 10, 100)
ax1.plot(x, np.sin(x), label='sin(x)', color='blue', linewidth=2)
ax1.plot(x, np.cos(x), '--', label='cos(x)', color='red')
ax1.set_title('三角函数')
ax1.set_xlabel('X轴')
ax1.set_ylabel('Y轴')
ax1.legend()
ax1.grid(True)
# 柱状图
departments = df['Department'].value_counts()
ax2.bar(departments.index, departments.values, color=['skyblue', 'lightgreen', 'salmon'])
ax2.set_title('部门分布')
ax2.set_ylabel('员工数量')
plt.tight_layout()
plt.show()
Seaborn基于Matplotlib,提供更高级的统计图表:
import seaborn as sns
# 设置主题
sns.set_theme(style="whitegrid")
# 创建图表
fig, axes = plt.subplots(2, 2, figsize=(15, 12))
# 散点图
sns.scatterplot(data=df, x='Age', y='Salary', hue='Department',
size='Salary', sizes=(50, 200), ax=axes[0, 0])
axes[0, 0].set_title('年龄与薪资关系')
# 箱线图
sns.boxplot(data=df, x='Department', y='Salary', ax=axes[0, 1])
axes[0, 1].set_title('部门薪资分布')
# 核密度估计图
sns.kdeplot(data=df, x='Salary', hue='Department', fill=True,
common_norm=False, palette='viridis', ax=axes[1, 0])
axes[1, 0].set_title('薪资分布密度')
# 热力图
corr = df.corr(numeric_only=True)
sns.heatmap(corr, annot=True, cmap='coolwarm', fmt=".2f", ax=axes[1, 1])
axes[1, 1].set_title('特征相关性')
plt.tight_layout()
plt.show()
可视化选择指南:
数值-数值 | ||
类别-数值 | ||
多变量 | ||
时间序列 |
SciPy提供高级科学计算功能:
from scipy import integrate, optimize
# 数值积分
result, error = integrate.quad(
lambda x: np.exp(-x**2), # 高斯函数
-np.inf, np.inf # 从负无穷到正无穷
)
print(f"高斯积分结果: {result:.5f} (±{error:.2e})")
# 函数优化
deff(x):
return (x - 2)**2 + np.sin(10*x)
# 寻找全局最小值
result = optimize.differential_evolution(f, bounds=[(0, 4)])
print(f"最小值位置: x={result.x[0]:.4f}, f(x)={result.fun:.4f}")
# 线性回归
from scipy import stats
x = np.array([1, 2, 3, 4, 5])
y = np.array([2.1, 3.8, 6.2, 8.1, 9.9])
slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
print(f"回归方程: y = {slope:.2f}x + {intercept:.2f}")
print(f"相关系数: {r_value:.3f}")
SciPy的线性代数模块功能强大:
from scipy import linalg
# 创建矩阵
A = np.array([[1, 2], [3, 4]])
b = np.array([5, 6])
# 解线性方程组
x = linalg.solve(A, b)
print(f"解向量: {x}")
# 特征值和特征向量
eigenvalues, eigenvectors = linalg.eig(A)
print("特征值:", eigenvalues)
print("特征向量:\n", eigenvectors)
# 奇异值分解
U, s, Vh = linalg.svd(A)
print("U矩阵:\n", U)
print("奇异值:", s)
print("Vh矩阵:\n", Vh)
# 生成模拟销售数据
dates = pd.date_range('2023-01-01', '2023-06-30')
products = ['A', 'B', 'C', 'D']
sales_data = {
'date': np.random.choice(dates, 500),
'product': np.random.choice(products, 500),
'revenue': np.random.uniform(100, 1000, 500),
'quantity': np.random.randint(1, 20, 500)
}
sales = pd.DataFrame(sales_data)
# 数据透视表
pivot = pd.pivot_table(
sales,
values='revenue',
index='product',
columns=pd.Grouper(key='date', freq='M'),
aggfunc='sum'
)
# 可视化
plt.figure(figsize=(14, 8))
plt.subplot(2, 1, 1)
sns.heatmap(pivot.fillna(0), cmap='YlGnBu', annot=True, fmt='.0f')
plt.title('月度产品销售额热力图')
plt.subplot(2, 1, 2)
monthly = sales.groupby(pd.Grouper(key='date', freq='M'))['revenue'].sum()
monthly.plot(kind='bar', color='skyblue', edgecolor='black')
plt.title('月度销售额趋势')
plt.ylabel('销售额')
plt.xticks(rotation=0)
plt.tight_layout()
plt.show()
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report, confusion_matrix
# 加载数据(示例使用葡萄酒数据集)
from sklearn.datasets import load_wine
wine = load_wine()
data = pd.DataFrame(wine.data, columns=wine.feature_names)
data['target'] = wine.target
# 数据预处理
X = data.drop('target', axis=1)
y = data['target']
# 特征缩放
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 数据集划分
X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y, test_size=0.2, random_state=42
)
# 模型训练
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# 模型评估
y_pred = model.predict(X_test)
print("分类报告:")
print(classification_report(y_test, y_pred))
# 混淆矩阵
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix(y_test, y_pred),
annot=True, fmt='d', cmap='Blues',
xticklabels=wine.target_names,
yticklabels=wine.target_names)
plt.title('混淆矩阵')
plt.ylabel('真实标签')
plt.xlabel('预测标签')
# 特征重要性
plt.figure(figsize=(10, 6))
importance = pd.Series(model.feature_importances_, index=wine.feature_names)
importance.sort_values().plot(kind='barh', color='teal')
plt.title('特征重要性')
plt.xlabel('重要性得分')
plt.show()
学习路径建议:
# 学习进度检查
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
defcheck_skills():
print("基础技能检查:")
# 创建数组
arr = np.random.randint(1, 100, size=(5, 5))
print("随机数组:\n", arr)
# 数据处理
df = pd.DataFrame(arr, columns=list('ABCDE'))
df['F'] = df['A'] + df['B']
print("\nDataFrame:\n", df.head())
# 可视化
plt.figure(figsize=(6, 4))
df.mean().plot(kind='bar', color='purple')
plt.title('各列平均值')
plt.ylabel('值')
plt.show()
print("\n✅ 已完成基础技能检查!")
check_skills()
掌握Python数据分析与可视化是数据科学领域的核心能力。通过本指南我们可以学习从基础数据处理到高级可视化及机器学习应用的完整流程,建议通过实际项目加深理解。持续练习是掌握这些技能的关键!
阅读原文:原文链接