I have a pandas data frame with both unordered and ordered categorical columns (as well as columns with other data types). I want to select only the ordered categorical columns.
Here's an example dataset:
import pandas as pd
import numpy.random as npr
n_obs = 20
eye_colors = ["blue", "brown"]
people = pd.DataFrame({
"eye_color": npr.choice(eye_colors, size=n_obs),
"age": npr.randint(20, 60, size=n_obs)
})
people["age_group"] = pd.cut(people["age"], [20, 30, 40, 50, 60], right=False)
people["eye_color"] = pd.Categorical(people["eye_color"], eye_colors)
Here, eye_color is an unordered categorical column, age_group is an ordered categorical column, and age is numeric. I want just the age_group column.
I can select all categorical columns with .select_dtypes().
categories = people.select_dtypes("category")
I could use a list comprehension with the .cat.ordered property to then limit this to only ordered categories.
categories[[col for col in categories.columns if categories[col].cat.ordered]]
This is dreadfully complicated code, so it feels like there must be a better way.
What's the idiomatic way of selecting only ordered columns from a dataframe?