SNIPPET
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.

COMMENTS
RELATED SNIPPETS
Pivoting Pandas Dataframes
Python
Data Preprocessing

Pandas

3
SparkSession instantiate
Python
Data Preprocessing

2
Converting Data Types
Python
Data Preprocessing

Data-cleaning

2
Data Minification
Python
Data Preprocessing

Cleaning

2
Search Snippets by Tag: