Categoricals in Python
A category column stores each label once, and can carry an order.
import pandas as pd
sizes = pd.Series(["small", "large", "medium", "small"])
ordered = sizes.astype(
pd.CategoricalDtype(["small", "medium", "large"], ordered=True))
print(ordered.cat.categories.tolist())
print(ordered.cat.codes.tolist())
print((ordered > "small").tolist())
print(ordered.sort_values().tolist())
How it works
- Casting to category alone saves memory on repeated strings.
- An ordered category compares and sorts the way you defined.
cat.categoriesandcat.codesshow the two halves.
Keywords and builtins used here
asprint
The run, in numbers
- Lines
- 10
- Characters to type
- 314
- Tokens
- 107
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 61 seconds.
Step 5 of 5 in Deriving columns, step 13 of 26 in pandas.