Created
October 17, 2024 02:33
-
-
Save minghao51/e1d0950d90cbd8ccd251dcfe9aa738d3 to your computer and use it in GitHub Desktop.
downcast/downcast.py at master · deepak7376/downcast · GitHub
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
import numpy as np | |
def reduce(df): | |
cols = df.dtypes.index.tolist() | |
types = df.dtypes.values.tolist() | |
for i,t in enumerate(types): | |
if 'int' in str(t): | |
if df[cols[i]].min() > np.iinfo(np.int8).min and df[cols[i]].max() < np.iinfo(np.int8).max: | |
df[cols[i]] = df[cols[i]].astype(np.int8) | |
elif df[cols[i]].min() > np.iinfo(np.int16).min and df[cols[i]].max() < np.iinfo(np.int16).max: | |
df[cols[i]] = df[cols[i]].astype(np.int16) | |
elif df[cols[i]].min() > np.iinfo(np.int32).min and df[cols[i]].max() < np.iinfo(np.int32).max: | |
df[cols[i]] = df[cols[i]].astype(np.int32) | |
else: | |
df[cols[i]] = df[cols[i]].astype(np.int64) | |
elif 'float' in str(t): | |
if df[cols[i]].min() > np.finfo(np.float16).min and df[cols[i]].max() < np.finfo(np.float16).max: | |
df[cols[i]] = df[cols[i]].astype(np.float16) | |
elif df[cols[i]].min() > np.finfo(np.float32).min and df[cols[i]].max() < np.finfo(np.float32).max: | |
df[cols[i]] = df[cols[i]].astype(np.float32) | |
else: | |
df[cols[i]] = df[cols[i]].astype(np.float64) | |
elif t == np.object: | |
if cols[i] == 'date': | |
df[cols[i]] = pd.to_datetime(df[cols[i]], format='%Y-%m-%d') | |
else: | |
df[cols[i]] = df[cols[i]].astype('category') | |
return df |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment