categorical
Categorical data
This is an introduction to pandas categorical data type, including a short comparison
with R’s factor.
Categoricals are a pandas data type corresponding to categorical variables in
statistics. A categorical variable takes on a limited, and usually fixed,
number of possible values (categories; levels in R). Examples are gender,
social class, blood type, country affiliation, observation time or rating via
Likert scales.
In contrast to statistical categorical variables, categorical data might have an order (e.g.
‘strongly agree’ vs ‘agree’ or ‘first observation’ vs. ‘second observation’), but numerical
operations (additions, divisions, …) are not possible.
All values of categorical data are either in categories or np.nan. Order is defined by
the order of categories, not lexical order of the values. Internally, the data structure
consists of a categories array and an integer array of codes which point to the real value in
the categories array.
The categorical data type is useful in the following cases:
- A string variable consisting of only a few different values. Converting such a string
variable to a categorical variable will save some memory, see here. - The lexical order of a variable is not the same as the logical order (“one”, “two”, “three”).
By converting to a categorical and specifying an order on the categories, sorting and
min/max will use the logical order instead of the lexical order, see here. - As a signal to other Python libraries that this column should be treated as a categorical
variable (e.g. to use suitable statistical methods or plot types).
See also the API docs on categoricals.
Object creation
Series creation
Categorical Series or columns in a DataFrame can be created in several ways:
By specifying dtype="category" when constructing a Series:
1 | In [1]: s = pd.Series(["a", "b", "c", "a"], dtype="category") |
By converting an existing Series or column to a category dtype:
1 | In [3]: df = pd.DataFrame({"A": ["a", "b", "c", "a"]}) |
By using special functions, such as cut(), which groups data into
discrete bins. See the example on tiling in the docs.
1 | In [6]: df = pd.DataFrame({'value': np.random.randint(0, 100, 20)}) |
By passing a pandas.Categorical object to a Series or assigning it to a DataFrame.
1 | In [10]: raw_cat = pd.Categorical(["a", "b", "c", "a"], categories=["b", "c", "d"], |
Categorical data has a specific category dtype:
1 | In [16]: df.dtypes |
DataFrame creation
Similar to the previous section where a single column was converted to categorical, all columns in aDataFrame can be batch converted to categorical either during or after construction.
This can be done during construction by specifying dtype="category" in the DataFrame constructor:
1 | In [17]: df = pd.DataFrame({'A': list('abca'), 'B': list('bccd')}, dtype="category") |
Note that the categories present in each column differ; the conversion is done column by column, so
only labels present in a given column are categories:
1 | In [19]: df['A'] |
New in version 0.23.0.
Analogously, all columns in an existing DataFrame can be batch converted using DataFrame.astype():
1 | In [21]: df = pd.DataFrame({'A': list('abca'), 'B': list('bccd')}) |
This conversion is likewise done column by column:
1 | In [24]: df_cat['A'] |
Controlling behavior
In the examples above where we passed dtype='category', we used the default
behavior:
- Categories are inferred from the data.
- Categories are unordered.
To control those behaviors, instead of passing 'category', use an instance
of CategoricalDtype.
1 | In [26]: from pandas.api.types import CategoricalDtype |
Similarly, a CategoricalDtype can be used with a DataFrame to ensure that categories
are consistent among all columns.
1 | In [31]: from pandas.api.types import CategoricalDtype |
::: tip Note
To perform table-wise conversion, where all labels in the entire DataFrame are used as
categories for each column, the categories parameter can be determined programmatically bycategories = pd.unique(df.to_numpy().ravel()).
:::
If you already have codes and categories, you can use thefrom_codes() constructor to save the factorize step
during normal constructor mode:
1 | In [37]: splitter = np.random.choice([0, 1], 5, p=[0.5, 0.5]) |
Regaining original data
To get back to the original Series or NumPy array, useSeries.astype(original_dtype) or np.asarray(categorical):
1 | In [39]: s = pd.Series(["a", "b", "c", "a"]) |
::: tip Note
In contrast to R’s factor function, categorical data is not converting input values to
strings; categories will end up the same data type as the original values.
:::
::: tip Note
In contrast to R’s factor function, there is currently no way to assign/change labels at
creation time. Use categories to change the categories after creation time.
:::
CategoricalDtype
Changed in version 0.21.0.
A categorical’s type is fully described by
categories: a sequence of unique values and no missing valuesordered: a boolean
This information can be stored in a CategoricalDtype.
The categories argument is optional, which implies that the actual categories
should be inferred from whatever is present in the data when thepandas.Categorical is created. The categories are assumed to be unordered
by default.
1 | In [45]: from pandas.api.types import CategoricalDtype |
A CategoricalDtype can be used in any place pandas
expects a dtype. For example pandas.read_csv(),pandas.DataFrame.astype(), or in the Series constructor.
::: tip Note
As a convenience, you can use the string 'category' in place of aCategoricalDtype when you want the default behavior of
the categories being unordered, and equal to the set values present in the
array. In other words, dtype='category' is equivalent todtype=CategoricalDtype().
:::
Equality semantics
Two instances of CategoricalDtype compare equal
whenever they have the same categories and order. When comparing two
unordered categoricals, the order of the categories is not considered.
1 | In [49]: c1 = CategoricalDtype(['a', 'b', 'c'], ordered=False) |
All instances of CategoricalDtype compare equal to the string 'category'.
1 | In [52]: c1 == 'category' |
::: danger Warning
Since dtype='category' is essentially CategoricalDtype(None, False),
and since all instances CategoricalDtype compare equal to 'category',
all instances of CategoricalDtype compare equal to aCategoricalDtype(None, False), regardless of categories orordered.
:::
Description
Using describe() on categorical data will produce similar
output to a Series or DataFrame of type string.
1 | In [53]: cat = pd.Categorical(["a", "c", "c", np.nan], categories=["b", "a", "c"]) |
Working with categories
Categorical data has a categories and a ordered property, which list their
possible values and whether the ordering matters or not. These properties are
exposed as s.cat.categories and s.cat.ordered. If you don’t manually
specify categories and ordering, they are inferred from the passed arguments.
1 | In [57]: s = pd.Series(["a", "b", "c", "a"], dtype="category") |
It’s also possible to pass in the categories in a specific order:
1 | In [60]: s = pd.Series(pd.Categorical(["a", "b", "c", "a"], |
::: tip Note
New categorical data are not automatically ordered. You must explicitly
pass ordered=True to indicate an ordered Categorical.
:::
::: tip Note
The result of unique() is not always the same as Series.cat.categories,
because Series.unique() has a couple of guarantees, namely that it returns categories
in the order of appearance, and it only includes values that are actually present.
1 | In [63]: s = pd.Series(list('babc')).astype(CategoricalDtype(list('abcd'))) |
:::
Renaming categories
Renaming categories is done by assigning new values to theSeries.cat.categories property or by using therename_categories() method:
1 | In [67]: s = pd.Series(["a", "b", "c", "a"], dtype="category") |
::: tip Note
In contrast to R’s factor, categorical data can have categories of other types than string.
:::
::: tip Note
Be aware that assigning new categories is an inplace operation, while most other operations
under Series.cat per default return a new Series of dtype category.
:::
Categories must be unique or a ValueError is raised:
1 | In [75]: try: |
Categories must also not be NaN or a ValueError is raised:
1 | In [76]: try: |
Appending new categories
Appending categories can be done by using theadd_categories() method:
1 | In [77]: s = s.cat.add_categories([4]) |
Removing categories
Removing categories can be done by using theremove_categories() method. Values which are removed
are replaced by np.nan.:
1 | In [80]: s = s.cat.remove_categories([4]) |
Removing unused categories
Removing unused categories can also be done:
1 | In [82]: s = pd.Series(pd.Categorical(["a", "b", "a"], |
Setting categories
If you want to do remove and add new categories in one step (which has some
speed advantage), or simply set the categories to a predefined scale,
use set_categories().
1 | In [85]: s = pd.Series(["one", "two", "four", "-"], dtype="category") |
::: tip Note
Be aware that Categorical.set_categories() cannot know whether some category is omitted
intentionally or because it is misspelled or (under Python3) due to a type difference (e.g.,
NumPy S1 dtype and Python strings). This can result in surprising behaviour!
:::
Sorting and order
If categorical data is ordered (s.cat.ordered == True), then the order of the categories has a
meaning and certain operations are possible. If the categorical is unordered, .min()/.max() will raise a TypeError.
1 | In [89]: s = pd.Series(pd.Categorical(["a", "b", "c", "a"], ordered=False)) |
You can set categorical data to be ordered by using as_ordered() or unordered by using as_unordered(). These will by
default return a new object.
1 | In [95]: s.cat.as_ordered() |
Sorting will use the order defined by categories, not any lexical order present on the data type.
This is even true for strings and numeric data:
1 | In [97]: s = pd.Series([1, 2, 3, 1], dtype="category") |
Reordering
Reordering the categories is possible via the Categorical.reorder_categories() and
the Categorical.set_categories() methods. For Categorical.reorder_categories(), all
old categories must be included in the new categories and no new categories are allowed. This will
necessarily make the sort order the same as the categories order.
1 | In [103]: s = pd.Series([1, 2, 3, 1], dtype="category") |
::: tip Note
Note the difference between assigning new categories and reordering the categories: the first
renames categories and therefore the individual values in the Series, but if the first
position was sorted last, the renamed value will still be sorted last. Reordering means that the
way values are sorted is different afterwards, but not that individual values in theSeries are changed.
:::
::: tip Note
If the Categorical is not ordered, Series.min() and Series.max() will raiseTypeError. Numeric operations like +, -, *, / and operations based on them
(e.g. Series.median(), which would need to compute the mean between two values if the length
of an array is even) do not work and raise a TypeError.
:::
Multi column sorting
A categorical dtyped column will participate in a multi-column sort in a similar manner to other columns.
The ordering of the categorical is determined by the categories of that column.
1 | In [109]: dfs = pd.DataFrame({'A': pd.Categorical(list('bbeebbaa'), |
Reordering the categories changes a future sort.
1 | In [111]: dfs['A'] = dfs['A'].cat.reorder_categories(['a', 'b', 'e']) |
Comparisons
Comparing categorical data with other objects is possible in three cases:
- Comparing equality (
==and!=) to a list-like object (list, Series, array,
…) of the same length as the categorical data. - All comparisons (
==,!=,>,>=,<, and<=) of categorical data to
another categorical Series, whenordered==Trueand the categories are the same. - All comparisons of a categorical data to a scalar.
All other comparisons, especially “non-equality” comparisons of two categoricals with different
categories or a categorical with any list-like object, will raise a TypeError.
::: tip Note
Any “non-equality” comparisons of categorical data with a Series, np.array, list or
categorical data with different categories or ordering will raise a TypeError because custom
categories ordering could be interpreted in two ways: one with taking into account the
ordering and one without.
:::
1 | In [113]: cat = pd.Series([1, 2, 3]).astype( |
Comparing to a categorical with the same categories and ordering or to a scalar works:
1 | In [119]: cat > cat_base |
Equality comparisons work with any list-like object of same length and scalars:
1 | In [121]: cat == cat_base |
This doesn’t work because the categories are not the same:
1 | In [124]: try: |
If you want to do a “non-equality” comparison of a categorical series with a list-like object
which is not categorical data, you need to be explicit and convert the categorical data back to
the original values:
1 | In [125]: base = np.array([1, 2, 3]) |
When you compare two unordered categoricals with the same categories, the order is not considered:
1 | In [128]: c1 = pd.Categorical(['a', 'b'], categories=['a', 'b'], ordered=False) |
Operations
Apart from Series.min(), Series.max() and Series.mode(), the
following operations are possible with categorical data:
Series methods like Series.value_counts() will use all categories,
even if some categories are not present in the data:
1 | In [131]: s = pd.Series(pd.Categorical(["a", "b", "c", "c"], |
Groupby will also show “unused” categories:
1 | In [133]: cats = pd.Categorical(["a", "b", "b", "b", "c", "c", "c"], |
Pivot tables:
1 | In [139]: raw_cat = pd.Categorical(["a", "a", "b", "b"], categories=["a", "b", "c"]) |
Data munging
The optimized pandas data access methods .loc, .iloc, .at, and .iat,
work as normal. The only difference is the return type (for getting) and
that only values already in categories can be assigned.
Getting
If the slicing operation returns either a DataFrame or a column of typeSeries, the category dtype is preserved.
1 | In [142]: idx = pd.Index(["h", "i", "j", "k", "l", "m", "n"]) |
An example where the category type is not preserved is if you take one single
row: the resulting Series is of dtype object:
1 | # get the complete "h" row as a Series |
Returning a single item from categorical data will also return the value, not a categorical
of length “1”.
1 | In [151]: df.iat[0, 0] |
::: tip Note
The is in contrast to R’s factor function, where factor(c(1,2,3))[1]
returns a single value factor.
:::
To get a single value Series of type category, you pass in a list with
a single value:
1 | In [154]: df.loc[["h"], "cats"] |
String and datetime accessors
The accessors .dt and .str will work if the s.cat.categories are of
an appropriate type:
1 | In [155]: str_s = pd.Series(list('aabb')) |
::: tip Note
The returned Series (or DataFrame) is of the same type as if you used the.str. / .dt. on a Series of that type (and not of
type category!).
:::
That means, that the returned values from methods and properties on the accessors of aSeries and the returned values from methods and properties on the accessors of thisSeries transformed to one of type category will be equal:
1 | In [163]: ret_s = str_s.str.contains("a") |
::: tip Note
The work is done on the categories and then a new Series is constructed. This has
some performance implication if you have a Series of type string, where lots of elements
are repeated (i.e. the number of unique elements in the Series is a lot smaller than the
length of the Series). In this case it can be faster to convert the original Series
to one of type category and use .str. or .dt. on that.
:::
Setting
Setting values in a categorical column (or Series) works as long as the
value is included in the categories:
1 | In [167]: idx = pd.Index(["h", "i", "j", "k", "l", "m", "n"]) |
Setting values by assigning categorical data will also check that the categories match:
1 | In [174]: df.loc["j":"k", "cats"] = pd.Categorical(["a", "a"], categories=["a", "b"]) |
Assigning a Categorical to parts of a column of other types will use the values:
1 | In [177]: df = pd.DataFrame({"a": [1, 1, 1, 1, 1], "b": ["a", "a", "a", "a", "a"]}) |
Merging
You can concat two DataFrames containing categorical data together,
but the categories of these categoricals need to be the same:
1 | In [182]: cat = pd.Series(["a", "b"], dtype="category") |
In this case the categories are not the same, and therefore an error is raised:
1 | In [188]: df_different = df.copy() |
The same applies to df.append(df_different).
See also the section on merge dtypes for notes about preserving merge dtypes and performance.
Unioning
New in version 0.19.0.
If you want to combine categoricals that do not necessarily have the same
categories, the union_categoricals() function will
combine a list-like of categoricals. The new categories will be the union of
the categories being combined.
1 | In [191]: from pandas.api.types import union_categoricals |
By default, the resulting categories will be ordered as
they appear in the data. If you want the categories to
be lexsorted, use sort_categories=True argument.
1 | In [195]: union_categoricals([a, b], sort_categories=True) |
union_categoricals also works with the “easy” case of combining two
categoricals of the same categories and order information
(e.g. what you could also append for).
1 | In [196]: a = pd.Categorical(["a", "b"], ordered=True) |
The below raises TypeError because the categories are ordered and not identical.
1 | In [1]: a = pd.Categorical(["a", "b"], ordered=True) |
New in version 0.20.0.
Ordered categoricals with different categories or orderings can be combined by
using the ignore_ordered=True argument.
1 | In [199]: a = pd.Categorical(["a", "b", "c"], ordered=True) |
union_categoricals() also works with aCategoricalIndex, or Series containing categorical data, but note that
the resulting array will always be a plain Categorical:
1 | In [202]: a = pd.Series(["b", "c"], dtype='category') |
::: tip Note
union_categoricals may recode the integer codes for categories
when combining categoricals. This is likely what you want,
but if you are relying on the exact numbering of the categories, be
aware.
1 | In [205]: c1 = pd.Categorical(["b", "c"]) |
:::
Concatenation
This section describes concatenations specific to category dtype. See Concatenating objects for general description.
By default, Series or DataFrame concatenation which contains the same categories
results in category dtype, otherwise results in object dtype.
Use .astype or union_categoricals to get category result.
1 | # same categories |
Following table summarizes the results of Categoricals related concatenations.
| arg1 | arg2 | result |
|---|---|---|
| category | category (identical categories) | category |
| category | category (different categories, both not ordered) | object (dtype is inferred) |
| category | category (different categories, either one is ordered) | object (dtype is inferred) |
| category | not category | object (dtype is inferred) |
Getting data in/out
You can write data that contains category dtypes to a HDFStore.
See here for an example and caveats.
It is also possible to write data to and reading data from Stata format files.
See here for an example and caveats.
Writing to a CSV file will convert the data, effectively removing any information about the
categorical (categories and ordering). So if you read back the CSV file you have to convert the
relevant columns back to category and assign the right categories and categories ordering.
1 | In [221]: import io |
The same holds for writing to a SQL database with to_sql.
Missing data
pandas primarily uses the value np.nan to represent missing data. It is by
default not included in computations. See the Missing Data section.
Missing values should not be included in the Categorical’s categories,
only in the values.
Instead, it is understood that NaN is different, and is always a possibility.
When working with the Categorical’s codes, missing values will always have
a code of -1.
1 | In [235]: s = pd.Series(["a", "b", np.nan, "a"], dtype="category") |
Methods for working with missing data, e.g. isna(), fillna(),dropna(), all work normally:
1 | In [238]: s = pd.Series(["a", "b", np.nan], dtype="category") |
Differences to R’s factor
The following differences to R’s factor functions can be observed:
- R’s levels are named categories.
- R’s levels are always of type string, while categories in pandas can be of any dtype.
- It’s not possible to specify labels at creation time. Use
s.cat.rename_categories(new_labels)
afterwards. - In contrast to R’s factor function, using categorical data as the sole input to create a
new categorical series will not remove unused categories but create a new categorical series
which is equal to the passed in one! - R allows for missing values to be included in its levels (pandas’ categories). Pandas
does not allow NaN categories, but missing values can still be in the values.
Gotchas
Memory usage
The memory usage of a Categorical is proportional to the number of categories plus the length of the data. In contrast,
an object dtype is a constant times the length of the data.
1 | In [242]: s = pd.Series(['foo', 'bar'] * 1000) |
::: tip Note
If the number of categories approaches the length of the data, the Categorical will use nearly the same or
more memory than an equivalent object dtype representation.
1 | In [245]: s = pd.Series(['foo%04d' % i for i in range(2000)]) |
:::
Categorical is not a numpy array
Currently, categorical data and the underlying Categorical is implemented as a Python
object and not as a low-level NumPy array dtype. This leads to some problems.
NumPy itself doesn’t know about the new dtype:
1 | In [248]: try: |
Dtype comparisons work:
1 | In [251]: dtype == np.str_ |
To check if a Series contains Categorical data, use hasattr(s, 'cat'):
1 | In [253]: hasattr(pd.Series(['a'], dtype='category'), 'cat') |
Using NumPy functions on a Series of type category should not work as Categoricals
are not numeric data (even in the case that .categories is numeric).
1 | In [255]: s = pd.Series(pd.Categorical([1, 2, 3, 4])) |
::: tip Note
If such a function works, please file a bug at https://github.com/pandas-dev/pandas!
:::
dtype in apply
Pandas currently does not preserve the dtype in apply functions: If you apply along rows you get
a Series of object dtype (same as getting a row -> getting one element will return a
basic type) and applying along columns will also convert to object. NaN values are unaffected.
You can use fillna to handle missing values before applying a function.
1 | In [257]: df = pd.DataFrame({"a": [1, 2, 3, 4], |
Categorical index
CategoricalIndex is a type of index that is useful for supporting
indexing with duplicates. This is a container around a Categorical
and allows efficient indexing and storage of an index with a large number of duplicated elements.
See the advanced indexing docs for a more detailed
explanation.
Setting the index will create a CategoricalIndex:
1 | In [260]: cats = pd.Categorical([1, 2, 3, 4], categories=[4, 2, 3, 1]) |
Side effects
Constructing a Series from a Categorical will not copy the inputCategorical. This means that changes to the Series will in most cases
change the original Categorical:
1 | In [266]: cat = pd.Categorical([1, 2, 3, 10], categories=[1, 2, 3, 4, 10]) |
Use copy=True to prevent such a behaviour or simply don’t reuse Categoricals:
1 | In [274]: cat = pd.Categorical([1, 2, 3, 10], categories=[1, 2, 3, 4, 10]) |
::: tip Note
This also happens in some cases when you supply a NumPy array instead of a Categorical:
using an int array (e.g. np.array([1,2,3,4])) will exhibit the same behavior, while using
a string array (e.g. np.array(["a","b","c","a"])) will not.
:::




