Python 数据科学工具链入门:NumPy、Pandas、Matplotlib 基础
介绍 Python 数据科学核心工具链。涵盖 NumPy 数值计算基础,包括数组创建、属性操作及向量化运算;Pandas 数据处理,涉及 DataFrame 构建、CSV 读取、缺失值清洗及特征工程;Matplotlib 与 Seaborn 可视化,展示直方图、散点图及热力图绘制。通过泰坦尼克号数据集实战,演示从数据加载、清洗到分析洞察的完整流程,并总结常见编码陷阱与最佳实践,为机器学习项目奠定基础。

介绍 Python 数据科学核心工具链。涵盖 NumPy 数值计算基础,包括数组创建、属性操作及向量化运算;Pandas 数据处理,涉及 DataFrame 构建、CSV 读取、缺失值清洗及特征工程;Matplotlib 与 Seaborn 可视化,展示直方图、散点图及热力图绘制。通过泰坦尼克号数据集实战,演示从数据加载、清洗到分析洞察的完整流程,并总结常见编码陷阱与最佳实践,为机器学习项目奠定基础。

机器学习算法是'菜谱',而 NumPy、Pandas、Matplotlib 构成了现代数据科学工作的基础设施。初学者若无法熟练使用这些工具,往往难以将想法转化为代码。
本文旨在帮助读者掌握三大核心库的基础用法,独立完成数据加载、清洗、探索及可视化的完整流程。
Anaconda 自带 Python、NumPy、Pandas、Matplotlib、Jupyter 等库,避免依赖冲突。
在终端中输入:
python --version
应显示 Python 3.9+。
然后启动 Jupyter Notebook:
jupyter notebook
浏览器会自动打开文件管理界面。
Python 原生 list 在科学计算中存在速度慢、不支持向量化运算的问题。NumPy 提供了高效的 ndarray 对象、广播机制及 C 语言底层实现。
import numpy as np
# 从列表创建
arr = np.array([1, 2, 3, 4])
print(arr)
# 创建全零/全一数组
zeros = np.zeros(5)
one = np.ones((2, 3))
# 创建等差数列
linspace = np.linspace(0, 10, 5)
# 创建随机数组
rand = np.random.rand(3, 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()
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# 元素级加法
print(a + b)
# 元素级乘法
print(a * b)
# 平方
print(a ** 2)
# 三角函数
print(np.sin(a))
# 条件筛选
print(a[a > 1])
arr = np.array([1, 2, 3, 4, 5])
print("均值:", np.mean(arr))
print("标准差:", np.std(arr))
print("最大值:", np.max(arr))
print("索引最大值:", np.argmax(arr))
print("求和:", np.sum(arr))
Pandas 提供了更贴近人类思维的数据结构:Series(一列数据)和 DataFrame(表格)。
import pandas as pd
data = {
'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35],
'city': ['NYC', 'LA', 'Chicago']
}
df = pd.DataFrame(data)
print(df)
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())
# 查看维度
print("形状:", titanic.shape)
# 统计摘要
print(titanic.describe())
# 查看分类变量分布
print(titanic['sex'].value_counts())
# 检查缺失值
print(titanic.isnull().sum())
# 单列(返回 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]
# 方案 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())
# 创建新特征:家庭规模
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']
# 直方图
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()
import seaborn as sns
# 生存率 vs 性别
plt.figure(figsize=(6, 4))
sns.barplot(x='sex', y='survived', data=titanic)
plt.title('不同性别的生存率')
plt.ylabel('生存概率')
plt.show()
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()
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))
# 舱位等级 vs 生存率
sns.barplot(x='pclass', y='survived', data=df, ax=axes[0, 0])
axes[0, 0].set_title('舱位等级与生存率')
# 是否独自旅行 vs 生存率
sns.barplot(x='is_alone', y='survived', data=df, ax=axes[0, 1])
axes[0, 1].set_title('独自旅行与生存率')
axes[0, 1].set_xticklabels(['否', '是'])
# 年龄分布对比
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()
# 票价分布
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()
关键洞察:
inplace=True直接修改原数据难以回溯。建议显式创建新对象:
df_clean = df.dropna()
错误写法:
df[df['age'] > 30]['fare'] = 100
正确写法:
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