pandas categorical codes code example

Example 1: display all categorical column in pandas dataframe

# get all categorical columns in the dataframe
catCols = [col for col in df.columns if df[col].dtype=="O"]

Example 2: using df.astype to select categorical data and numerical data

df = pd.DataFrame({'vertebrates': ['Bird', 'Bird', 'Mammal', 'Fish', 'Amphibian', 'Reptile', 'Mammal']})

df.vertebrates.astype("category").cat.codes

Example 3: using df.astype to select categorical data and numerical data

df.satisfaction.astype("category",
  ordered=True,
  categories=ordered_satisfaction
)