typestar

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

  1. Casting to category alone saves memory on repeated strings.
  2. An ordered category compares and sorts the way you defined.
  3. cat.categories and cat.codes show the two halves.

Keywords and builtins used here

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.

Type this snippet

Step 5 of 5 in Deriving columns, step 13 of 26 in pandas.

← Previous Next →