Appearance
内存优化
处理大数据集时,内存优化是提高性能的关键。
查看内存使用
python
import pandas as pd
import numpy as np
# 创建示例数据
df = pd.DataFrame({
'A': np.random.randint(0, 100, 1000000),
'B': np.random.randn(1000000),
'C': np.random.choice(['X', 'Y', 'Z'], 1000000)
})
# 查看内存使用
print(df.memory_usage(deep=True))
print(f"总内存: {df.memory_usage(deep=True).sum() / 1024**2:.2f} MB")
# 使用info查看
print(df.info(memory_usage='deep'))数值类型优化
python
# 优化前
print("优化前内存:")
print(df[['A', 'B']].memory_usage(deep=True))
# 优化整数类型
df['A'] = df['A'].astype('int8') # 如果数值范围小,使用int8
# 优化浮点数类型
df['B'] = df['B'].astype('float32')
print("\n优化后内存:")
print(df[['A', 'B']].memory_usage(deep=True))类别类型优化
python
# 优化前
print(f"字符串列内存: {df['C'].memory_usage(deep=True) / 1024**2:.2f} MB")
# 转换为类别类型
df['C'] = df['C'].astype('category')
print(f"类别列内存: {df['C'].memory_usage(deep=True) / 1024**2:.2f} MB")自动类型优化
python
def optimize_memory(df):
"""自动优化DataFrame内存"""
start_mem = df.memory_usage().sum() / 1024**2
for col in df.columns:
col_type = df[col].dtype
if col_type != object:
c_min = df[col].min()
c_max = df[col].max()
if str(col_type)[:3] == 'int':
if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:
df[col] = df[col].astype(np.int8)
elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:
df[col] = df[col].astype(np.int16)
elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:
df[col] = df[col].astype(np.int32)
else:
if c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:
df[col] = df[col].astype(np.float32)
else:
if df[col].nunique() / len(df) < 0.5:
df[col] = df[col].astype('category')
end_mem = df.memory_usage().sum() / 1024**2
print(f"内存优化: {start_mem:.2f} MB -> {end_mem:.2f} MB ({100 * (start_mem - end_mem) / start_mem:.1f}%减少)")
return df
# 应用优化
df_optimized = optimize_memory(df.copy())分块处理
python
# 大文件分块读取
chunk_size = 100000
chunks = []
for chunk in pd.read_csv('large_file.csv', chunksize=chunk_size):
# 处理每个块
processed_chunk = chunk[chunk['列名'] > 0] # 示例处理
chunks.append(processed_chunk)
# 合并结果
df_result = pd.concat(chunks, ignore_index=True)选择性读取
python
# 只读取需要的列
df = pd.read_csv('large_file.csv', usecols=['列A', '列B'])
# 指定数据类型读取
dtypes = {
'列A': 'int32',
'列B': 'float32',
'列C': 'category'
}
df = pd.read_csv('large_file.csv', dtype=dtypes)删除不必要的副本
python
# 避免不必要的副本
# 不好的做法
df_copy = df.copy() # 如果不需要修改,避免复制
# 好的做法
# 直接在原DataFrame上操作或使用视图
df['新列'] = df['A'] * 2 # 不会创建副本使用迭代器
python
# 大文件逐行处理
with pd.read_csv('large_file.csv', chunksize=1000) as reader:
for chunk in reader:
# 处理每个块
process(chunk)内存优化可以显著提高处理大数据集的能力,是数据分析的重要技能。