Optimizing Memory Usage with Category Data Types in Pandas
Instruction: Discuss how and when to use category data types in Pandas for optimizing DataFrame memory usage.
Context: This question tests the candidate's knowledge on optimizing memory usage in Pandas, a vital skill for handling large datasets efficiently.
Updated
Official answer available
Read the opening below, then unlock the full answer and practical guidance.
Categorical columns store integer codes plus a category dictionary. They are often useful for repeated labels with low cardinality, but can use more memory when most values are distinct. Measure on the actual dtype/backend and operations.
import pandas as pd s = pd.Series(["north", "south", "north", None], dtype="string") cat = s.astype("category") assert cat.astype("string").equals(s) assert cat.cat.codes.tolist() == [0,...