from tqdm import tqdm
# 压缩内存函数,文件大小没变化,占用内存减小
def reduce_mem_usage(df):
start_memory = df.memory_usage().sum() / 1024 ** 2
numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
for col in tqdm(df.columns):
col_type = df[col].dtypes
if col_type in numerics:
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)
elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:
df[col] = df[col].astype(np.int64)
else:
if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:
df[col] = df[col].astype(np.float16)
elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:
df[col] = df[col].astype(np.float32)
else:
df[col] = df[col].astype(np.float64)
end_mem = df.memory_usage().sum() / 1024 ** 2
print("start memory usage is {}MB,memory usage after optimization is {}MB".format(round(start_memory,2),round(end_mem,2)))
print("Compress Rate: {0:.2%}".format((start_memory - end_mem) / start_memory))
return df
pandas数据压缩75%内存
于 2023-10-13 01:13:46 首次发布