Python 数据科学工具链入门:NumPy、Pandas、Matplotlib 快速上手
Python 数据科学基础工具 NumPy、Pandas、Matplotlib 及 Seaborn 的核心用法与实战流程。涵盖环境搭建、数组创建与运算、DataFrame 数据处理、缺失值清洗、特征工程及可视化分析。通过泰坦尼克号数据集演示从数据加载到洞察生成的完整链路,帮助初学者建立数据分析工作流并规避常见编码陷阱。

Python 数据科学基础工具 NumPy、Pandas、Matplotlib 及 Seaborn 的核心用法与实战流程。涵盖环境搭建、数组创建与运算、DataFrame 数据处理、缺失值清洗、特征工程及可视化分析。通过泰坦尼克号数据集演示从数据加载到洞察生成的完整链路,帮助初学者建立数据分析工作流并规避常见编码陷阱。

'工欲善其事,必先利其器。' ——在机器学习的世界里,你的'器'就是 Python 数据科学工具链。
想象你要做一道菜。即使你背熟了所有食谱,如果厨房里只有生锈的刀、没校准的秤、漏底的锅,你依然做不出好菜。
机器学习也是如此。 算法是'菜谱',而 NumPy、Pandas、Matplotlib 就是你的'刀、秤、锅'——它们构成了现代数据科学工作的基础设施。
很多初学者一上来就急着学'神经网络''梯度提升',却连如何读取一个 CSV 文件都磕磕绊绊。结果是:想法很丰满,代码跑不动。
本文的目标很明确: ✅ 让你掌握三大核心库的基础用法; ✅ 能独立完成 数据加载 → 清洗 → 探索 → 可视化 的完整流程; ✅ 为后续所有机器学习项目打下坚实工具基础。
不需要你成为专家,但要让你不再被工具卡住。
💡 Anaconda 自带 Python、NumPy、Pandas、Matplotlib、Jupyter 等几乎所有你需要的库,避免依赖冲突。
在终端中输入:
python --version
应显示 Python 3.9+。
然后启动 Jupyter Notebook(推荐交互式开发环境):
jupyter notebook
浏览器会自动打开一个文件管理界面——这就是你的'数据实验室'。
🔧 替代方案:如果你已用
pip管理 Python,可手动安装:
pip install numpy pandas matplotlib seaborn jupyter
Python 原生的 list 虽然灵活,但在科学计算中存在两大问题:
而 NumPy(Numerical Python) 提供了:
📌 记住:几乎所有数据科学库(Pandas、scikit-learn、TensorFlow)都基于 NumPy 构建。
import numpy as np
# 从列表创建
arr = np.array([1, 2, 3, 4])
print(arr) # [1 2 3 4]
# 创建全零/全一数组
zeros = np.zeros(5) # [0. 0. 0. 0. 0.]
ones = np.ones((2, 3)) # 2x3 全 1 矩阵
# 创建等差数列
linspace = np.linspace(0, 10, 5) # [0. 2.5 5. 7.5 10.]
# 创建随机数组
rand = np.random.rand(3, 2) # 3x2,值在 [0,1) 之间
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)
# [[1 2]
# [3 4]
# [5 6]]
# 展平为一维
flat = arr.flatten() # [1 2 3 4 5 6]
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)) # [0.8415 0.9093 0.1411]
# 条件筛选
print(a[a > 1]) # [2 3]
✅ 关键优势:这些操作在 C 层面并行执行,速度极快。
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
💡 这些函数将贯穿你未来的模型评估、特征工程等环节。
如果说 NumPy 是'引擎',那么 Pandas 就是'驾驶舱'——它提供了更贴近人类思维的数据结构。
| 结构 | 维度 | 类比 |
|---|---|---|
Series | 1D | 带标签的一列数据(如 Excel 的一列) |
DataFrame | 2D | 表格(如 Excel 工作表) |
import pandas as pd
# 从字典创建
data = {
'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35],
'city': ['NYC', 'LA', 'Chicago']
}
df = pd.DataFrame(data)
print(df)
输出:
name age city
0 Alice 25 NYC
1 Bob 30 LA
2 Charlie 35 Chicago
我们将使用经典的 泰坦尼克号乘客数据集(titanic.csv),可从 Kaggle 下载,或使用 seaborn 内置版本:
# 方法 1:从 seaborn 加载(推荐初学者)
import seaborn as sns
titanic = sns.load_dataset('titanic')
# 方法 2:从本地 CSV 读取
# titanic = pd.read_csv('titanic.csv')
print("前 5 行:")
print(titanic.head())
print("\n基本信息:")
print(titanic.info())
典型输出:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 15 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 survived 891 non-null int64
1 pclass 891 non-null int64
2 sex 891 non-null object
3 age 714 non-null float64
...
🔍 注意:
age和embarked有缺失值(Non-Null Count < 891)——这是真实数据的常态!
# 查看维度
print("形状:", titanic.shape) # (891, 15)
# 统计摘要(仅数值列)
print(titanic.describe())
# 查看分类变量分布
print(titanic['sex'].value_counts())
# male 577
# female 314
# 检查缺失值
print(titanic.isnull().sum())
# age 177
# embarked 2
# deck 688 ← 大量缺失,可能需删除
# 单列(返回 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] # 前 3 行,前 5 列
⚠️ 注意:
&代替and,|代替or,且条件要用括号包围。
# 方案 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()) # 应为 0
✅ 最佳实践:记录你做了什么处理,因为这直接影响模型效果。
# 创建新特征:家庭规模 = 兄弟姐妹 + 父母子女 + 自己
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())
🌟 这些操作正是后续机器学习中'特征工程'的核心内容。
'一图胜千言'——在数据科学中,可视化是理解、沟通、发现的关键。
import matplotlib.pyplot as plt
# 设置中文字体(避免乱码)
plt.rcParams['font.sans-serif'] = ['SimHei'] # Windows
# plt.rcParams['font.family'] = 'Arial Unicode MS' # macOS
# 示例 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()
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()
输出将清晰显示:女性生存率远高于男性(约 74% vs 19%)。
# 年龄 vs 票价,颜色表示是否生存
plt.figure(figsize=(8, 6))
sns.scatterplot(
x='age',
y='fare',
hue='survived',
data=titanic,
alpha=0.7
)
plt.title('年龄与票价的关系(按生存状态着色)')
plt.show()
# 选择数值列
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()
🔍 你会发现
pclass(舱位等级)与fare(票价)高度负相关(-0.55)——头等舱票价高,等级数字小(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)
df['family_size'] = df['sibsp'] + df['parch'] + 1
df['is_alone'] = (df['family_size'] == 1).astype(int)
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、is_alone、age都是强预测特征。
inplace=True虽然 df.dropna(inplace=True) 看似方便,但它会直接修改原数据,难以回溯。建议:
df_clean = df.dropna() # 显式创建新对象
错误写法:
df[df['age'] > 30]['fare'] = 100 # 可能报 SettingWithCopyWarning
正确写法:
df.loc[df['age'] > 30, 'fare'] = 100
np.random.seed(42)通过本文,你已经掌握了:
后续内容将深入探讨:
这些内容将直接决定你未来模型的上限。
记住:工具的价值不在'知道',而在'用过'。 你敲下的每一行代码,都在为未来的智能系统铺路。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online