3 Upvotes

Convert All Non-numeric Columns to Category Data Types

Python
Data Preprocessing

Converts all object data types in a dataframe to category data types. Useful for when training models such as Catboost where categorical fields need to be provided as category data types.

from pandas.api.types import is_numeric_dtype  
def convert_cats(df):
        cats = []
        for col in df.columns:
            if is_numeric_dtype(df[col]):
                pass
            else:
                cats.append(col)
        for col in cats:
            df[col] = df[col].astype('category')
convert_cats(X)

By detro - Last Updated Jan. 5, 2021, 9:44 a.m.

Did you find this snippet useful?

Sign up to bookmark this in your snippet library

COMMENTS
RELATED SNIPPETS
Pivoting Pandas Dataframes
Python
Data Preprocessing

Pandas

3
2
Top Contributors
103
100