Python 数据科学工具链入门:NumPy、Pandas、Matplotlib 快速上手
一、为什么工具链如此重要?
机器学习算法是'菜谱',而 NumPy、Pandas、Matplotlib 构成了现代数据科学工作的基础设施。初学者若连如何读取 CSV 文件都困难,会导致想法无法落地。
本文目标:
- 掌握三大核心库的基础用法;
- 独立完成数据加载 → 清洗 → 探索 → 可视化的完整流程;
- 为后续机器学习项目打下坚实工具基础。
二、环境准备
推荐方式:使用 Anaconda
- 访问 https://www.anaconda.com/products/distribution
- 下载对应操作系统的安装包(Windows / macOS / Linux)
- 安装时勾选 'Add to PATH'(Windows 用户注意)
- 安装完成后,打开 Anaconda Prompt(Windows)或终端(macOS/Linux)
💡 Anaconda 自带 Python、NumPy、Pandas、Matplotlib、Jupyter 等几乎所有你需要的库,避免依赖冲突。
验证安装
在终端中输入:
python --version
应显示 Python 3.9+。
然后启动 Jupyter Notebook(推荐交互式开发环境):
jupyter notebook
浏览器会自动打开一个文件管理界面。
三、NumPy:高效数值计算的基石
为什么需要 NumPy?
Python 原生的 list 在科学计算中存在速度慢、不支持向量化运算的问题。NumPy 提供了高效的多维数组对象 ndarray、广播机制及 C 语言底层实现。
1. 创建数组
import numpy as np
# 从列表创建
arr = np.array([1, 2, 3, 4])
print(arr)
# [1 2 3 4]
# 创建全零/全一数组
zeros = np.zeros(5)
ones = np.ones((2, 3))
# 创建等差数列
linspace = np.linspace(0, 10, 5)
# 创建随机数组
rand = np.random.rand(3, 2)
2. 数组属性与形状操作
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("形状:", arr.shape) # (2, 3)
print("维度:", arr.ndim) # 2
print("元素总数:", arr.size) # 6
print("数据类型:", arr.dtype) # int64
# 改变形状(不改变数据)
reshaped = arr.reshape(3, 2)
print(reshaped)
# 展平为一维
flat = arr.flatten()
3. 向量化运算
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(a ** 2) # [1 4 9]
# 三角函数
print(np.sin(a))
# 条件筛选
print(a[a > 1]) # [2 3]
4. 常用数学函数
arr = np.array([1, 2, 3, 4, 5])
print("均值:", np.mean(arr)) # 3.0
print("标准差:", np.std(arr)) # 1.414...
print("最大值:", np.max(arr)) # 5
print("索引最大值:", np.argmax(arr)) # 4
print("求和:", np.sum(arr)) # 15
四、Pandas:让数据处理像 Excel 一样直观
核心数据结构
| 结构 | 维度 | 类比 |
|---|---|---|
| Series | 1D | 带标签的一列数据 |
| DataFrame | 2D | 表格 |
1. 创建 DataFrame
import pandas as pd
data = {
'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35],
'city': ['NYC', 'LA', 'Chicago']
}
df = pd.DataFrame(data)
print(df)
2. 读取真实数据
import seaborn as sns
# 方法 1:从 seaborn 加载(推荐初学者)
titanic = sns.load_dataset('titanic')
# 方法 2:从本地 CSV 读取
# titanic = pd.read_csv('titanic.csv')
print("前 5 行:")
print(titanic.head())
print("\n基本信息:")
print(titanic.info())
3. 基础探索
# 查看维度
print("形状:", titanic.shape)
# 统计摘要(仅数值列)
print(titanic.describe())
# 查看分类变量分布
print(titanic['sex'].value_counts())
# 检查缺失值
print(titanic.isnull().sum())
4. 数据筛选与索引
# 单列(返回 Series)
ages = titanic['age']
# 多列(返回 DataFrame)
subset = titanic[['name', 'age', 'fare']]
# 条件筛选
survived_females = titanic[(titanic['survived'] == 1) & (titanic['sex'] == 'female')]
# 使用 .loc(基于标签)
first_row = titanic.loc[0, ['name', 'age']]
# 使用 .iloc(基于位置)
first_three = titanic.iloc[:3, :5]
5. 处理缺失值
# 方案 1:删除含缺失的行
titanic_clean1 = titanic.dropna()
# 方案 2:用均值填充年龄
titanic['age'].fillna(titanic['age'].mean(), inplace=True)
# 方案 3:用众数填充登船港口
mode_embarked = titanic['embarked'].mode()[0]
titanic['embarked'].fillna(mode_embarked, inplace=True)
print(titanic[['age', 'embarked']].isnull().sum())
6. 特征工程初探
# 创建新特征:家庭规模
titanic['family_size'] = titanic['sibsp'] + titanic['parch'] + 1
# 分箱:将年龄分为儿童/成人/老人
titanic['age_group'] = pd.cut(
titanic['age'], bins=[0, 18, 65, 100], labels=['Child', 'Adult', 'Senior'])
# 编码分类变量
titanic['sex_encoded'] = titanic['sex'].map({'male': 0, 'female': 1})
print(titanic[['age', 'age_group', 'sex', 'sex_encoded']].head())
五、Matplotlib 与 Seaborn:用图表讲好数据故事
1. Matplotlib:基础绘图库
import matplotlib.pyplot as plt
# 设置中文字体(避免乱码)
plt.rcParams['font.sans-serif'] = ['SimHei']
# 示例 1:直方图(年龄分布)
plt.figure(figsize=(8, 5))
plt.hist(titanic['age'], bins=20, color='skyblue', edgecolor='black')
plt.title('泰坦尼克号乘客年龄分布')
plt.xlabel('年龄')
plt.ylabel('人数')
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()
2. Seaborn:统计可视化利器
import seaborn as sns
# 示例 2:生存率 vs 性别(柱状图)
plt.figure(figsize=(6, 4))
sns.barplot(x='sex', y='survived', data=titanic)
plt.title('不同性别的生存率')
plt.ylabel('生存概率')
plt.show()
3. 散点图:探索变量关系
plt.figure(figsize=(8, 6))
sns.scatterplot(
x='age', y='fare', hue='survived', data=titanic, alpha=0.7)
plt.title('年龄与票价的关系(按生存状态着色)')
plt.show()
4. 热力图:查看相关性
numeric_cols = titanic.select_dtypes(include=['number']).columns
corr_matrix = titanic[numeric_cols].corr()
plt.figure(figsize=(10, 8))
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', center=0)
plt.title('数值特征相关性热力图')
plt.show()
六、端到端实战:从原始数据到洞察
步骤 1:加载与清洗
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset('titanic')
# 基础清洗
df['age'].fillna(df['age'].median(), inplace=True)
df.drop(columns=['deck', 'embark_town'], inplace=True)
df.dropna(subset=['embarked'], inplace=True)
步骤 2:创建新特征
df['family_size'] = df['sibsp'] + df['parch'] + 1
df['is_alone'] = (df['family_size'] == 1).astype(int)
步骤 3:可视化关键发现
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# 1. 舱位等级 vs 生存率
sns.barplot(x='pclass', y='survived', data=df, ax=axes[0, 0])
axes[0, 0].set_title('舱位等级与生存率')
# 2. 是否独自旅行 vs 生存率
sns.barplot(x='is_alone', y='survived', data=df, ax=axes[0, 1])
axes[0, 1].set_title('独自旅行与生存率')
axes[0, 1].set_xticklabels(['否', '是'])
# 3. 年龄分布对比
df[df['survived'] == 1]['age'].hist(alpha=0.7, label='生存', ax=axes[1, 0])
df[df['survived'] == 0]['age'].hist(alpha=0.7, label='遇难', ax=axes[1, 0])
axes[1, 0].set_title('年龄分布对比')
axes[1, 0].legend()
# 4. 票价分布(对数尺度)
df.boxplot(column='fare', by='survived', ax=axes[1, 1])
axes[1, 1].set_yscale('log')
axes[1, 1].set_title('票价分布(对数尺度)')
plt.tight_layout()
plt.show()
关键洞察:
- 头等舱(pclass=1)生存率最高;
- 结伴旅行者生存率更高;
- 儿童(<10 岁)生存率明显提升;
- 高票价乘客更可能生存。
七、常见陷阱与最佳实践
1. 不要滥用 inplace=True
建议显式创建新对象:
df_clean = df.dropna()
2. 避免链式索引
错误写法:
df[df['age'] > 30]['fare'] = 100
正确写法:
df.loc[df['age'] > 30, 'fare'] = 100
3. 可视化前先检查数据分布
- 对长尾分布使用对数尺度;
- 添加标题、坐标轴标签、图例。
4. 保持代码可复现
- 设置随机种子:
np.random.seed(42) - 记录 Pandas/NumPy 版本。
八、下一步学习方向
通过本文,你已经掌握了:
- 用 NumPy 高效处理数值;
- 用 Pandas 清洗、转换、探索表格数据;
- 用 Matplotlib/Seaborn 可视化发现规律。
后续可深入探讨:
- 数据质量的五大维度;
- 高级缺失值处理策略;
- 异常值检测与处理;
- 特征缩放(标准化、归一化)。


