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 array and an integer array of which point to the real value in
the array.
categories
codes
categories
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).
In [16]: df.dtypesOut[16]: A objectB categorydtype: object
DataFrame creation
Similar to the previous section where a single column was converted to categorical, all columns in a
DataFrame 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:
In [17]: df=pd.DataFrame({"A":list("abca"),"B":list("bccd")},dtype
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.
In [26]: frompandas.api.typesimportCategoricalDtypeIn [27]: s=pd.Series(["a","b"
Regaining original data
To get back to the original Series or NumPy array, use
Series.astype(original_dtype) or np.asarray(categorical):
In [39]: s=pd.Series(["a","b","c","a"])In [40]: sOut[40]: 0 a1 b2 c3 a
CategoricalDtype
A categorical’s type is fully described by
categories: a sequence of unique values and no missing values
ordered: 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 the
pandas.Categorical is created. The categories are assumed to be unordered
by default.
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.
In [49]: c1=CategoricalDtype(["a","b","c"],ordered=False)# Equal, since order is not considered when ordered=FalseIn [50]: c1==CategoricalDtype(["b",
Description
Using describe() on categorical data will produce similar
output to a Series or DataFrame of type string.
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.
Appending categories can be done by using the
add_categories() method:
In [76]: s=s.cat.add_categories([4])In [77]: s.cat.categoriesOut[77]: Index(['Group a', 'Group b', 'Group c', 4], dtype='object')In [78]: sOut[78]: 0 Group a1 Group b2 Group c3 Group adtype: category
Removing categories
Removing categories can be done by using the
remove_categories() method. Values which are removed
are replaced by np.nan.:
In [79]: s=s.cat.remove_categories([4])In [80]: sOut[80]: 0 Group a1 Group b2 Group c3 Group adtype: categoryCategories (3, object): ['Group a', 'Group b', 'Group c']
Removing unused categories
Removing unused categories can also be done:
In [81]: s=pd.Series(pd.Categorical(["a","b","a"],categories=["a","b","c","d"]))In [82]: sOut[82]: 0 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().
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.
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:
In [96]: s=pd.Series([1,2,3,1],dtype="category")In [97]: s=s.cat.set_categories([2,3,1],ordered=True)
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.
In [102]: s=pd.Series([1,2,3,1],dtype="category")In [103]:
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.
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, when ordered==True and 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.
In [112]: cat=pd.Series([1,2,3]).astype(CategoricalDtype([3,2,1],ordered=True))In [113]: cat_base=pd.Series([2,2
Comparing to a categorical with the same categories and ordering or to a scalar works:
This doesn’t work because the categories are not the same:
In [123]: try: .....: cat>cat_base2 .....: exceptTypeErrorase: .....: print("TypeError:",str(e)) .....: TypeError: Categoricals can only be compared if 'categories' are the same.
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:
Series methods like Series.value_counts() will use all categories,
even if some categories are not present in the data:
In [130]: s=pd.Series(pd.Categorical(["a","b","c","c"],categories=["c","a","b","d"]))In [131]: s.value_counts()Out[131]: c 2a 1b 1d 0Name: count, dtype: int64
DataFrame methods like DataFrame.sum() also show “unused” categories when observed=False.
In [132]: columns=pd.Categorical( .....: ["One","One","Two"],categories=["One","Two","Three"],ordered=True .....: ) .....: In [133]: df=pd.DataFrame(
Groupby will also show “unused” categories when observed=False:
In [135]: cats=pd.Categorical( .....: ["a","b","b","b","c","c","c"],categories=["a","b","c","d"] .....: ) .....:
Pivot tables:
In [141]: raw_cat=pd.Categorical(["a","a","b","b"],categories=["a","b","c"])In [142]: df=pd.DataFrame({"A":raw_cat,"B":[
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 type
Series, the category dtype is preserved.
In [144]: idx=pd.Index(["h","i","j","k","l","m","n"])In [145]: cats=pd.Series(["a","b","b","b","c","c","c"],dtype="category",index=idx)In [146]: values=[1,2,2,2,3,4,5]In [147]: df=pd.DataFrame({"cats":cats,"values":values},index=idx)In [148]: df.iloc[2:4,:]Out[148]: cats valuesj b 2k b 2In [149]: df.iloc[2:4,:].dtypesOut[149]: cats categoryvalues int64dtype: objectIn [150]: df.loc["h":"j","cats"]Out[150]: h ai bj bName: cats, dtype: categoryCategories (3, object): ['a', 'b', 'c']In [151]: df[df["cats"]=="b"]Out[151]: cats valuesi b 2j b 2k b 2
An example where the category type is not preserved is if you take one single
row: the resulting Series is of dtype object:
# get the complete "h" row as a SeriesIn [152]: df.loc["h",:]Out[152]: cats avalues 1Name: h, dtype: object
Returning a single item from categorical data will also return the value, not a categorical
of length “1”.
In [153]: df.iat[0,0]Out[153]: 'a'In [154]: df["cats"]=df["cats"].cat.rename_categories(["x","y","z"])In [155]: df.at[
To get a single value Series of type category, you pass in a list with
a single value:
In [156]: df.loc[["h"],"cats"]Out[156]: h xName: cats, dtype: categoryCategories (3, object): ['x', 'y', 'z']
String and datetime accessors
The accessors .dt and .str will work if the s.cat.categories are of
an appropriate type:
In [157]: str_s=pd.Series(list("aabb"))In [158]: str_cat=str_s.astype("category")In [159]: str_cat
Setting
Setting values in a categorical column (or Series) works as long as the
value is included in the categories:
In [169]: idx=pd.Index(["h","i","j","k","l","m","n"])In [170]: cats=pd.
Merging / concatenation
By default, combining Series or DataFrames which contain the same
categories results in category dtype, otherwise results will depend on the
dtype of the underlying categories. Merges that result in non-categorical
dtypes will likely have higher memory usage. Use .astype or
union_categoricals to ensure category results.
In [184]: frompandas.api.typesimportunion_categoricals# same categories
Unioning
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.
In [195]: frompandas.api.typesimportunion_categoricalsIn [196]: a=pd.Categorical(["b","c"])In [197]: b=pd
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.
In [221]: importioIn [222]: s=pd.Series(pd.Categorical(["a","b","b","a","a","d"]))# rename the categoriesIn [223]: s=s.cat.rename_categories(["very good","good","bad"])# reorder the categories and add missing categoriesIn [224]: s=s.cat.set_categories(["very bad","bad","medium","good","very good"])In [225]: df=pd.DataFrame({"cats":s,"vals":[1,2,3,4,5,6]})In [226]: csv=io.StringIO()In [227]: df.to_csv(csv)In [228]: df2=pd.read_csv(io.StringIO(csv.getvalue()))In [229]: df2.dtypesOut[229]: Unnamed: 0 int64cats objectvals int64dtype: objectIn [230]: df2["cats"]Out[230]: 0 very good1 good2 good3 very good4 very good5 badName: cats, dtype: object# Redo the categoryIn [231]: df2["cats"]=df2["cats"].astype("category")In [232]: df2["cats"]=df2["cats"].cat.set_categories( .....: ["very bad","bad","medium","good","very good"] .....: ) .....: In [233]: df2.dtypesOut[233]: Unnamed: 0 int64cats categoryvals int64dtype: objectIn [234]: df2["cats"]Out[234]: 0 very good1 good2 good3 very good4 very good5 badName: cats, dtype: categoryCategories (5, object): ['very bad', 'bad', 'medium', 'good', 'very good']
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.
In [235]: s=pd.Series(["a","b",np.nan,"a"],dtype="category")# only two categoriesIn [236]: sOut[236]: 0 a1 b2 NaN3 adtype: categoryCategories (2, object): ['a', 'b']In [237]: s.cat.codesOut[237]: 0 01 12 -13 0dtype: int8
Methods for working with missing data, e.g. isna(), fillna(),
dropna(), all work normally:
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.
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:
In [248]: try: .....: np.dtype("category") .....: exceptTypeErrorase:
dtype in apply
pandas currently does not preserve the dtype in apply functions: If you apply along rows you get
a Series of objectdtype (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.
In [257]: df=pd.DataFrame( .....: { .....: "a":[
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:
In [260]: cats=pd.Categorical([1,2,3,4],categories
Side effects
Constructing a Series from a Categorical will not copy the input
Categorical. This means that changes to the Series will in most cases
change the original Categorical:
In [266]: cat=pd.Categorical([1,2,3,10],categories
0 a a
1 b b
2 c c
3 a a
9
)
for
i
in
range
(
0
,
100
,
10
)]
In [8]:
df
[
"group"
]
=
pd
.
cut
(
df
.
value
,
range
(
0
,
105
,
10
),
right
=
False
,
labels
=
labels
)
In [9]:
df
.
head
(
10
)
Out[9]:
value group
0 65 60 - 69
1 49 40 - 49
2 56 50 - 59
3 43 40 - 49
4 43 40 - 49
5 91 90 - 99
6 32 30 - 39
7 87 80 - 89
8 36 30 - 39
9 8 0 - 9
.
Series
(
raw_cat
)
In [12]:
s
Out[12]:
0 NaN
1 b
2 c
3 NaN
dtype: category
Categories (3, object): ['b', 'c', 'd']
In [13]:
df
=
pd
.
DataFrame
({
"A"
:
[
"a"
,
"b"
,
"c"
,
"a"
]})
In [14]:
df
[
"B"
]
=
raw_cat
In [15]:
df
Out[15]:
A B
0 a NaN
1 b b
2 c c
3 a NaN
=
"category"
)
In [18]:
df
.
dtypes
Out[18]:
A category
B category
dtype: object
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:
In [110]: dfs["A"]=dfs["A"].cat.reorder_categories(["a","b","e"])In [111]: dfs.sort_values(by=["A","B"])Out[111]: A B7 a 16 a 20 b 15 b 11 b 24 b 22 e 13 e 2
,
2
])
.
astype
(
CategoricalDtype
([
3
,
2
,
1
],
ordered
=
True
))
In [114]:
cat_base2
=
pd
.
Series
([
2
,
2
,
2
])
.
astype
(
CategoricalDtype
(
ordered
=
True
))
In [115]:
cat
Out[115]:
0 1
1 2
2 3
dtype: category
Categories (3, int64): [3 < 2 < 1]
In [116]:
cat_base
Out[116]:
0 2
1 2
2 2
dtype: category
Categories (3, int64): [3 < 2 < 1]
In [117]:
cat_base2
Out[117]:
0 2
1 2
2 2
dtype: category
Categories (1, int64): [2]
dtype: bool
TypeError: Cannot compare a Categorical for op __gt__ with type <class 'numpy.ndarray'>.
If you want to compare values, use 'np.asarray(cat) <op> other'.
That means, that the returned values from methods and properties on the accessors of a
Series and the returned values from methods and properties on the accessors of this
Series transformed to one of type category will be equal:
TypeError: Cannot setitem on a Categorical with a new category, set the categories first
Setting values by assigning categorical data will also check that the categories match:
In [176]: df.loc["j":"k","cats"]=pd.Categorical(["a","a"],categories=["a","b"])In [177]: dfOut[177]: cats valuesh a 1i a 1j a 2k a 2l a 1m a 1n a 1In [178]: try: .....: df.loc["j":"k","cats"]=pd.Categorical(["b","b"],categories=["a","b","c"]) .....: exceptTypeErrorase: .....: print("TypeError:",str(e)) .....: TypeError: Cannot set a Categorical with another, without identical categories
Assigning a Categorical to parts of a column of other types will use the values:
In [179]: df=pd.DataFrame({"a":[1,1,1,1,1],"b":["a","a","a","a","a"]})In [180]: df.loc[1:2,"a"]=pd.Categorical(["b","b"],categories=["a","b"])In [181]: df.loc[2:3,"b"]=pd.Categorical(["b","b"],categories=["a","b"])In [182]: dfOut[182]: a b0 1 a1 b a2 b b3 1 b4 1 aIn [183]: df.dtypesOut[183]: a objectb objectdtype: object
In [185]:
s1
=
pd
.
Series
([
"a"
,
"b"
],
dtype
=
"category"
)
In [186]:
s2
=
pd
.
Series
([
"a"
,
"b"
,
"a"
],
dtype
=
"category"
)
In [187]:
pd
.
concat
([
s1
,
s2
])
Out[187]:
0 a
1 b
0 a
1 b
2 a
dtype: category
Categories (2, object): ['a', 'b']
# different categories
In [188]:
s3
=
pd
.
Series
([
"b"
,
"c"
],
dtype
=
"category"
)
In [189]:
pd
.
concat
([
s1
,
s3
])
Out[189]:
0 a
1 b
0 b
1 c
dtype: object
# Output dtype is inferred based on categories values
In [190]:
int_cats
=
pd
.
Series
([
1
,
2
],
dtype
=
"category"
)
In [191]:
float_cats
=
pd
.
Series
([
3.0
,
4.0
],
dtype
=
"category"
)
In [192]:
pd
.
concat
([
int_cats
,
float_cats
])
Out[192]:
0 1.0
1 2.0
0 3.0
1 4.0
dtype: float64
In [193]:
pd
.
concat
([
s1
,
s3
])
.
astype
(
"category"
)
Out[193]:
0 a
1 b
0 b
1 c
dtype: category
Categories (3, object): ['a', 'b', 'c']
In [194]:
union_categoricals
([
s1
.
array
,
s3
.
array
])
Out[194]:
['a', 'b', 'b', 'c']
Categories (3, object): ['a', 'b', 'c']
The following table summarizes the results of merging Categoricals:
arg1
arg2
identical
result
category
category
True
category
category (object)
category (object)
False
object (dtype is inferred)
category (int)
category (float)
False
float (dtype is inferred)
.
Categorical
([
"a"
,
"b"
])
In [198]:
union_categoricals
([
a
,
b
])
Out[198]:
['b', 'c', 'a', 'b']
Categories (3, object): ['b', 'c', 'a']
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.
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).
The below raises TypeError because the categories are ordered and not identical.
In [203]: a=pd.Categorical(["a","b"],ordered=True)In [204]: b=pd.Categorical(["a","b","c"],ordered=True)In [205]: union_categoricals([a,b])---------------------------------------------------------------------------TypeErrorTraceback (most recent call last)
CellIn[205],line1----> 1union_categoricals([a,b])File ~/work/pandas/pandas/pandas/core/dtypes/concat.py:341, in union_categoricals(to_union, sort_categories, ignore_order)339ifall(c.orderedforcinto_union):340msg="to union ordered Categoricals, all categories must be the same"--> 341raiseTypeError(msg)342raiseTypeError("Categorical.ordered must be the same")344ifignore_order:TypeError: to union ordered Categoricals, all categories must be the same
Ordered categoricals with different categories or orderings can be combined by
using the ignore_ordered=True argument.
union_categoricals() also works with a
CategoricalIndex, or Series containing categorical data, but note that
the resulting array will always be a plain Categorical:
TypeError: Cannot interpret 'CategoricalDtype(categories=['a'], ordered=False, categories_dtype=object)' as a data type
Dtype comparisons work:
In [251]: dtype==np.str_Out[251]: FalseIn [252]: np.str_==dtypeOut[252]: False
To check if a Series contains Categorical data, use hasattr(s,'cat'):
In [253]: hasattr(pd.Series(["a"],dtype="category"),"cat")Out[253]: TrueIn [254]: hasattr(pd.Series(["a"]),"cat")Out[254]: False
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).
In [255]: s=pd.Series(pd.Categorical([1,2,3,4]))In [256]: try: .....: np.sum(s) .....: exceptTypeErrorase: .....: print("TypeError:",str(e)) .....: TypeError: 'Categorical' with dtype category does not support reduction 'sum'