如何查看DataFrame占用的内存?有哪些减少内存占用的方法?
进阶机器学习
答题要点
import pandas as pd
import numpy as np
# 1. 查看内存
df.info(memory_usage='deep')
# 或者
print(df.memory_usage(deep=True).sum() / 1024**2, "MB")
# 2. 优化数值类型 (Downcast)
# 默认int64占8字节,int8只占1字节
# 用 pd.to_numeric 自动降维
df['int_col'] = pd.to_numeric(df['int_col'], downcast='integer')
df['float_col'] = pd.to_numeric(df['float_col'], downcast='float')
# 或者手动指定
# int8: -128 to 127
# int16: -32768 to 32767
df['age'] = df['age'].astype('int8') # 年龄肯定在0-120之间
# 3. 优化对象类型 (Object -> Category)
# 当唯一值较少时(cardinality ratio low)
df['city'] = df['city'].astype('category')
# 4. 读取时就指定类型 (避免读取后再转换的内存峰值)
dtypes = {'age': 'int8', 'city': 'category'}
df = pd.read_csv('data.csv', dtype=dtypes)
# 5. 只读取需要的列
df = pd.read_csv('data.csv', usecols=['age', 'city'])
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题