0
0

More than 1 year has passed since last update.

メモリ使用量を削減する

Last updated at Posted at 2023-08-28
import numpy as np

def reduce_mem_usage(df, verbose=True):
    # 数値型のデータ型を定義
    numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
    
    # 初期のメモリ使用量を計算
    start_mem = df.memory_usage().sum() / 1024**2
    
    # 各列ごとにメモリ使用量を削減
    for col in 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
    
    # メモリ使用量の削減率を表示
    if verbose:
        print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) / start_mem))
    
    # 処理後のDataFrameを返す
    return df

通常、読み込んだデータのデフォルトのデータ型はint64float64が指定されています。

上記は、Pandasのデータフレームのメモリ使用量を削減するための関数です。

この関数を呼び出すことで、データ型を最適化することによってデータフレームのメモリ使用量を削減できます。ただし、注意点として、データ型の変換によって一部の精度が失われる可能性があるため、十分なテストと検討が必要です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0