아미(아름다운미소)

메모리 최적화 자동화 본문

랭귀지/pandas

메모리 최적화 자동화

유키공 2025. 3. 27. 10:53
# 기존 메모리 사용량 확인
df.info(memory_usage='deep')

# 정수형 컬럼 최적화
int_cols = df.select_dtypes(include=['int64']).columns
df[int_cols] = df[int_cols].apply(pd.to_numeric, downcast='integer')

# 실수형 컬럼 최적화
float_cols = df.select_dtypes(include=['float64']).columns
df[float_cols] = df[float_cols].apply(pd.to_numeric, downcast='float')

# 문자열 컬럼은 범주형으로 변환 (고유값이 적은 경우)
obj_cols = df.select_dtypes(include=['object']).columns
for col in obj_cols:
    if df[col].nunique() / len(df[col]) < 0.5:  # 고유값이 50% 미만일 때
        df[col] = df[col].astype('category')

# 최적화 후 메모리 사용량 확인
df.info(memory_usage='deep')

 

 

def optimize_memory(df):
    # 수치형 데이터 다운캐스트
    for col in df.select_dtypes(include=['integer']).columns:
        df[col] = pd.to_numeric(df[col], downcast='integer')
    for col in df.select_dtypes(include=['float']).columns:
        df[col] = pd.to_numeric(df[col], downcast='float')
    
    # 카테고리 변환 (고유값 20개 이하)
    for col in df.select_dtypes(include=['object']).columns:
        if df[col].nunique() <= 20:
            df[col] = df[col].astype('category')
    
    # 불린 타입 변환
    for col in df.select_dtypes(include=['bool']).columns:
        df[col] = df[col].astype('bool')
    
    # 날짜 변환
    for col in df.select_dtypes(include=['object']).columns:
        if df[col].head().str.match(r'\d{4}-\d{2}-\d{2}').all():
            df[col] = pd.to_datetime(df[col])
    
    return df

# 사용 예시
df = optimize_memory(df)

'랭귀지 > pandas' 카테고리의 다른 글

df비교  (0) 2025.03.27
데이터프레임의 메모리 사용량을 최적화하는 함수  (0) 2025.03.27
category로 변환  (0) 2025.03.27
함수 실행 시간 측정  (0) 2025.03.26
merge  (0) 2025.03.26
Comments