랭귀지/pandas

dataframe 타입지정

유키공 2025. 7. 30. 17:50
def process_dataframe_optimized(dict_df_types, df):
    type_handlers = {
        'int': lambda s: pd.to_numeric(s, errors='coerce').fillna(0).astype('int32'),
        'float': lambda s: pd.to_numeric(s, errors='coerce').fillna(0).astype('float32'),
        'bool': lambda s: s.astype(str).str.lower().isin(['true', 't', '1']),
        'datetime': lambda s: pd.to_datetime(s, errors='coerce'),
        'string': lambda s: s.astype('string').fillna(''),  # 빈 문자열로 채우기
        'category': lambda s: s.fillna('').astype('category')  # 빈 문자열로 채우기
    }
    
    # 교집합으로 존재하는 컬럼만 선택 (속도 향상)
    valid_cols = set(df.columns) & set(dict_df_types.keys())
    
    # 한 번에 모든 컬럼 처리 (assign 사용)
    return df.assign(**{
        col: type_handlers[dtype](df[col]) 
        for col, dtype in dict_df_types.items() 
        if col in valid_cols and dtype in type_handlers
    })