Pandas Categorical Type (Categorical)
Categorical is a data type in Pandas used to handle a finite set of category values, especially suitable for enumerated data such as gender, education level, grade, etc. The categorical type can significantly reduce memory usage and improve computational performance.
Create Categorical data
Create from a Series
Example
import
pandas
as
pd
Create categorical data
s
=
pd.
Series
(
[
"male"
,
"female"
,
"male"
,
"female"
,
"male"
]
,
dtype
=
"category"
)
(
"Basic categorical data:"
)
(
s
)
(
f
"Type: {s.dtype}"
)
(
)
Specify the category order
s2
=
pd.
Series
(
[
"Low"
,
"Center"
,
"High"
,
"Center"
,
"Low"
]
,
dtype
=
pd.
CategoricalDtype
(
categories
=
[
"Low"
,
"Center"
,
"High"
]
,
ordered
=
True
)
)
(
"Ordered categorical:"
)
(
s2
)
(
f
"Category order: {s2.dtype.categories.tolist()}"
)
Create from a list
Example
import
pandas
as
pd
Use pd.Categorical
categories
=
pd.
Categorical
(
[
"A"
,
"B"
,
"A"
,
"C"
,
"B"
]
,
categories
=
[
"A"
,
"B"
,
"C"
]
)
s
=
pd.
Series
(
categories
)
(
"Created from Categorical:"
)
(
s
)
Category attributes and methods
Access category information
Example
import
pandas
as
pd
s
=
pd.
Series
(
[
"Low"
,
"Center"
,
"High"
,
"Center"
,
"Low"
]
,
dtype
=
pd.
CategoricalDtype
(
categories
=
[
"Low"
,
"Center"
,
"High"
]
,
ordered
=
True
)
)
Category attributes
(
f
"Categories: {s.dtype.categories.tolist()}"
)
(
f
"Is ordered: {s.dtype.ordered}"
)
(
)
Count each category
(
"Category counts:"
)
(
s.
value_counts
(
)
)
Modify categories
Example
import
pandas
as
pd
s
=
pd.
Series
(
[
"A"
,
"B"
,
"C"
,
"A"
,
"B"
]
,
dtype
=
"category"
)
(
"Modified category names:"
)
s2
=
s.
cat
.
rename_categories
(
{
"A"
:
"Excellent"
,
"B"
:
"Good"
,
"C"
:
"Pass"
}
)
(
s2
)
(
)
Add a new category
(
"Added category:"
)
s3
=
s.
cat
.
add_categories
(
[
"D"
]
)
(
s3.
dtype
.
categories
.
tolist
(
)
)
(
)
Remove a category
(
"Removed category:"
)
s4
=
s.
cat
.
remove_categories
(
[
"C"
]
)
(
s4.
dtype
.
categories
.
tolist
(
)
)
Ordered categories
Ordered categories support comparison operations, suitable for categorical data with a magnitude order.
Example
import
pandas
as
pd
Create ordered categories
s
=
pd.
Series
(
[
"Low"
,
"Center"
,
"High"
,
"High"
,
"Low"
,
"Center"
]
,
dtype
=
pd.
CategoricalDtype
(
categories
=
[
"Low"
,
"Center"
,
"High"
]
,
ordered
=
True
)
)
Comparison Operations
(
"High > Medium:"
,
s
"Center"
)
(
"Medium > Low:"
,
s
"Low"
)
(
)
Sorting
(
"After sorting:"
)
(
s.
sort_values
(
)
)
Practical: Data grouping
Example
import
pandas
as
pd
Simulate user level data
users
=
pd.
DataFrame
(
{
"User ID"
:
range
(
1
,
1001
)
,
"Level"
: pd.
Categorical
(
[
"VIP"
]
100
[
"Gold"
]
300
[
"Silver"
]
400
[
"Regular"
]
200
,
categories
=
[
"Regular"
,
"Silver"
,
"Gold"
,
"VIP"
]
,
ordered
=
True
)
,
"Spending"
:
[
1000
,
500
,
100
,
50
]
250
}
)
(
"User level distribution:"
)
(
users
[
"Level"
]
.
value_counts
(
)
.
sort_index
(
)
)
(
)
Group and count by level
(
"Statistics by level:"
)
(
users.
groupby
(
"Level"
,
observed
=
True
)
[
"Spending"
]
.
sum
(
)
)
Memory Optimization
The categorical type can greatly reduce the memory usage of string data.
Example
import
pandas
as
pd
import
numpy
as
np
Create a large amount of repeated string data
np.
random
.
seed
(
42
)
s_str
=
pd.
Series
(
np.
random
.
choice
(
[
"Beijing"
,
"Shanghai"
,
"Guangzhou"
,
"Shenzhen"
]
,
1000000
)
)
Convert to categorical type
s_cat
=
s_str.
astype
(
"category"
)
Memory comparison
(
f
"String type memory: {s_str.memory_usage(deep=True) / 1024 / 1024:.2f} MB"
)
(
f
"Categorical type memory: {s_cat.memory_usage(deep=True) / 1024 / 1024:.2f} MB"
)
(
f
"Saved: {(1 - s_cat.memory_usage(deep=True) / s_str.memory_usage(deep=True)) * 100:.1f}%"
)
When data contains a large number of repeated string values, using the categorical type can significantly reduce memory usage, especially for large datasets.