跳到主要内容

Python 数据分析速查表

本文档汇总了 Python 数据分析中最常用的命令和技巧,方便快速查阅。

目录


NumPy 速查

数组创建

import numpy as np

# 从列表创建
arr = np.array([1, 2, 3])

# 创建特殊数组
np.zeros(5) # 全零数组
np.ones(5) # 全一数组
np.full(5, 7) # 指定值数组
np.arange(10) # 序列数组 [0,1,2,...,9]
np.linspace(0, 10, 5) # 等间距数组
np.eye(3) # 单位矩阵

# 随机数组
np.random.rand(5) # 0-1均匀分布
np.random.randn(5) # 标准正态分布
np.random.randint(0, 10, 5) # 整数随机
np.random.choice([1,2,3], 5) # 随机选择

数组属性

arr.ndim        # 维度数量
arr.shape # 形状 (2, 3)
arr.size # 元素总数
arr.dtype # 数据类型
arr.itemsize # 元素字节数

数组索引

arr[0]           # 单个元素
arr[-1] # 最后一个元素
arr[1:4] # 切片
arr[arr > 3] # 布尔索引
arr[[0, 2, 4]] # 整数数组索引

# 二维数组
arr[0] # 第一行
arr[0, 0] # 第一行第一列
arr[:, 0] # 第一列
arr[0:2, 0:2] # 子矩阵

数组运算

# 算术运算
arr + 1 # 加
arr - 1 # 减
arr * 2 # 乘
arr / 2 # 除
arr ** 2 # 幂

# 聚合函数
arr.sum() # 求和
arr.mean() # 平均值
arr.std() # 标准差
arr.min() # 最小值
arr.max() # 最大值

# 按轴运算
arr.sum(axis=0) # 按列
arr.sum(axis=1) # 按行

数组操作

arr.reshape(3, 4)  # 改变形状
arr.flatten() # 展平
arr.T # 转置
np.concatenate([a, b]) # 拼接
np.split(arr, 3) # 分割

Pandas 速查

DataFrame 创建

import pandas as pd

# 从字典创建
df = pd.DataFrame({
'name': ['张三', '李四'],
'age': [25, 30]
})

# 从CSV读取
df = pd.read_csv('file.csv')

# 从Excel读取
df = pd.read_excel('file.xlsx')

# 从字典列表创建
data = [{'name': '张三', 'age': 25}]
df = pd.DataFrame(data)

数据查看

df.head()        # 前5行
df.tail() # 后5行
df.shape # 形状 (行, 列)
df.columns # 列名
df.dtypes # 数据类型
df.info() # 信息摘要
df.describe() # 统计摘要

数据选择

# 选择列
df['name'] # 单列 (Series)
df[['name', 'age']] # 多列 (DataFrame)

# 选择行
df.loc[0] # 按标签
df.iloc[0] # 按位置

# 条件筛选
df[df['age'] > 25]
df.query('age > 25')
df[df['name'].isin(['张三', '李四'])]

数据操作

# 添加列
df['new_col'] = df['age'] * 2

# 删除列
df.drop('col', axis=1)
df.drop(columns=['a', 'b'])

# 删除行
df.drop(0)

# 排序
df.sort_values('age')
df.sort_index()

# 去重
df.drop_duplicates()

缺失值处理

df.isnull()           # 检测缺失值
df.isnull().sum() # 缺失值数量
df.fillna(0) # 填充缺失值
df.dropna() # 删除缺失值
df.interpolate() # 插值填充

分组聚合

# 分组
df.groupby('column')

# 聚合
df.groupby('column')['value'].sum()
df.groupby('column')['value'].agg(['sum', 'mean', 'count'])

# 透视表
pd.pivot_table(df, values='value', index='row', columns='col')

数据合并

# 连接
pd.concat([df1, df2]) # 纵向拼接
pd.concat([df1, df2], axis=1) # 横向拼接

# 合并
pd.merge(df1, df2, on='key') # 内连接
pd.merge(df1, df2, on='key', how='left') # 左连接

数据读写

# CSV
df.to_csv('file.csv', index=False)

# Excel
df.to_excel('file.xlsx', sheet_name='Sheet1')

# JSON
df.to_json('file.json', orient='records')

Matplotlib 速查

基础图表

import matplotlib.pyplot as plt

# 折线图
plt.plot(x, y)

# 散点图
plt.scatter(x, y)

# 柱状图
plt.bar(x, height)

# 直方图
plt.hist(data, bins=30)

# 饼图
plt.pie(sizes, labels=labels)

# 箱线图
plt.boxplot(data)

图表元素

plt.title('标题', fontsize=16)
plt.xlabel('X轴标签')
plt.ylabel('Y轴标签')
plt.legend() # 图例
plt.grid(True) # 网格
plt.xlim(0, 10) # X轴范围
plt.ylim(0, 10) # Y轴范围
plt.xticks([0, 5, 10], ['零', '五', '十']) # 刻度

样式和颜色

# 颜色
plt.plot(x, y, color='red')
plt.plot(x, y, c='#FF5733')
plt.plot(x, y, color='0.5') # 灰度

# 线条样式
plt.plot(x, y, linestyle='--') # 虚线
plt.plot(x, y, linewidth=2) # 线宽
plt.plot(x, y, marker='o') # 标记

# 子图
fig, axes = plt.subplots(2, 2) # 2x2子图
axes[0, 0].plot(x, y)

保存图表

plt.savefig('figure.png', dpi=300, bbox_inches='tight')
plt.savefig('figure.pdf')

常用技巧

数据类型转换

# 转换为数值
pd.to_numeric(df['col'])
df['col'].astype(int)

# 转换为日期
pd.to_datetime(df['date'])

# 转换为字符串
df['col'].astype(str)

字符串操作

df['col'].str.lower()       # 转小写
df['col'].str.upper() # 转大写
df['col'].str.strip() # 去除空白
df['col'].str.replace('a', 'b') # 替换
df['col'].str.contains('a') # 包含
df['col'].str.split(',') # 分割

条件逻辑

# if-else
df['new_col'] = df['col'].apply(lambda x: 'A' if x > 10 else 'B')

# np.where
df['new_col'] = np.where(df['col'] > 10, 'A', 'B')

# 多条件
df['new_col'] = np.select(
[cond1, cond2, cond3],
[val1, val2, val3],
default='other'
)

迭代操作

# 遍历DataFrame
for index, row in df.iterrows():
print(row['name'])

# 遍历列
for col in df.columns:
print(df[col])

随机操作

# 随机抽样
df.sample(n=10) # 随机10行
df.sample(frac=0.5) # 随机50%

# 随机打乱
df.sample(frac=1).reset_index(drop=True)

常用统计

# 描述统计
df.describe()
df['col'].describe()

# 相关性
df.corr()

# 分位数
df.quantile(0.5) # 中位数
df.quantile([0.25, 0.5, 0.75]) # 四分位数

管道操作

(df
.pipe(clean_data)
.filter(conditions)
.groupby('column')
.agg({'value': 'sum'})
)

Cheat Sheet 速查表

NumPy 速查

功能命令
创建数组np.array([1,2,3])
零数组np.zeros(5)
序列np.arange(10)
形状arr.shape
索引arr[0]
切片arr[1:4]
布尔索引arr[arr>5]
求和arr.sum()
平均值arr.mean()

Pandas 速查

功能命令
读取CSVpd.read_csv()
查看数据df.head()
选择列df['col']
条件筛选df[df['col']>10]
分组df.groupby('col')
聚合.agg({'col': 'sum'})
合并pd.merge()
透视表pd.pivot_table()
保存df.to_csv()

Matplotlib 速查

功能命令
折线图plt.plot(x, y)
散点图plt.scatter(x, y)
柱状图plt.bar(x, height)
直方图plt.hist(data)
标题plt.title('标题')
标签plt.xlabel()
图例plt.legend()
网格plt.grid(True)
保存plt.savefig()

参考资源