第13章:Python 数据分析与可视化
在大数据时代,数据分析与可视化是至关重要的技能。Python 提供了多个强大的库,如 NumPy、Pandas、Matplotlib 和 Seaborn,用于数据处理、分析和可视化。本章将介绍如何使用 Python 进行数据分析,并通过可视化技术更直观地呈现数据。
13.1 数据分析基础
13.1.1 什么是数据分析?
数据分析的主要流程包括:
- 数据收集:从数据库、API 或文件(CSV、Excel)获取数据。
- 数据清洗:处理缺失值、去除重复数据、格式化数据。
- 数据处理:计算统计值、转换数据格式。
- 数据可视化:使用图表直观展示数据。
- 数据建模与预测(高级部分)。
13.1.2 安装必要的库
pip install numpy pandas matplotlib seaborn
13.2 使用 NumPy 进行数值计算
NumPy(Numerical Python)是 Python 进行高效数值计算的核心库,提供强大的 数组(ndarray) 操作能力。
13.2.1 创建 NumPy 数组
python">import numpy as np
# 创建一维数组
arr = np.array([1, 2, 3, 4, 5])
print(arr)
# 创建 3x3 矩阵
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(matrix)
13.2.2 NumPy 常见操作
python"># 生成 0-9 的数组
arr = np.arange(10)
print(arr)
# 计算均值、标准差、最大值、最小值
print(arr.mean(), arr.std(), arr.max(), arr.min())
# 生成随机数
rand_arr = np.random.rand(3, 3) # 生成 3x3 随机数矩阵
print(rand_arr)
13.3 使用 Pandas 进行数据处理
Pandas 提供了两种主要的数据结构:
- Series:一维数组(类似列表)。
- DataFrame:二维表格(类似 Excel)。
13.3.1 创建 Pandas 数据结构
python">import pandas as pd
# 创建 Series
s = pd.Series([1, 3, 5, 7, 9])
print(s)
# 创建 DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Salary': [5000, 7000, 9000]}
df = pd.DataFrame(data)
print(df)
13.3.2 读取 CSV 文件
python">df = pd.read_csv("data.csv") # 读取 CSV 文件
print(df.head()) # 显示前 5 行数据
13.3.3 数据清洗
python"># 处理缺失值
df.dropna(inplace=True) # 删除含 NaN 的行
df.fillna(0, inplace=True) # 用 0 填充 NaN
# 删除重复数据
df.drop_duplicates(inplace=True)
# 数据类型转换
df['Age'] = df['Age'].astype(int)
# 数据筛选
df_filtered = df[df['Salary'] > 6000] # 筛选工资大于 6000 的员工
print(df_filtered)
13.4 数据可视化
Python 提供了多个可视化库,最常用的是 Matplotlib 和 Seaborn。
13.4.1 使用 Matplotlib 进行基本绘图
python">import matplotlib.pyplot as plt
# 折线图
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
plt.plot(x, y, marker='o', linestyle='-', color='b')
plt.title("折线图示例")
plt.xlabel("X 轴")
plt.ylabel("Y 轴")
plt.show()
13.4.2 使用 Seaborn 进行高级绘图
Seaborn 是基于 Matplotlib 的高级绘图库,支持美观的数据可视化。
python">import seaborn as sns
# 加载示例数据集
df = sns.load_dataset("iris")
# 绘制散点图
sns.scatterplot(x="sepal_length", y="sepal_width", hue="species", data=df)
plt.show()
13.4.3 直方图
python">sns.histplot(df["sepal_length"], bins=20, kde=True)
plt.show()
13.4.4 相关性热图
python"># 计算数据相关性
corr = df.corr()
# 绘制热力图
sns.heatmap(corr, annot=True, cmap="coolwarm", linewidths=0.5)
plt.title("相关性热图")
plt.show()
13.5 机器学习中的数据预处理(入门)
数据分析的最终目标之一是为机器学习做准备,以下是常见的数据预处理技术:
13.5.1 归一化与标准化
python">from sklearn.preprocessing import StandardScaler, MinMaxScaler
scaler = StandardScaler() # 标准化
df_scaled = scaler.fit_transform(df[["sepal_length", "sepal_width"]])
python">scaler = MinMaxScaler() # 归一化
df_scaled = scaler.fit_transform(df[["sepal_length", "sepal_width"]])
13.5.2 独热编码(One-Hot Encoding)
python">df = pd.get_dummies(df, columns=["species"])
print(df.head())
13.6 小结
本章介绍了:
- NumPy 进行高效数值计算。
- Pandas 进行数据处理和清洗。
- Matplotlib 和 Seaborn 进行数据可视化。
- 数据预处理,为机器学习建模做好准备。