Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Categorical Type (Categorical)

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"

)

print

(

"Basic categorical data:"

)

print

(

s

)

print

(

f

"Type: {s.dtype}"

)

print

(

)

Specify the category order

s2

=

pd.

Series

(

   

[

"Low"

,

"Center"

,

"High"

,

"Center"

,

"Low"

]

,

    dtype

=

pd.

CategoricalDtype

(

categories

=

[

"Low"

,

"Center"

,

"High"

]

,

ordered

=

True

)

)

print

(

"Ordered categorical:"

)

print

(

s2

)

print

(

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

)

print

(

"Created from Categorical:"

)

print

(

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

print

(

f

"Categories: {s.dtype.categories.tolist()}"

)

print

(

f

"Is ordered: {s.dtype.ordered}"

)

print

(

)

Count each category

print

(

"Category counts:"

)

print

(

s.

value_counts

(

)

)

Modify categories

Example

import

pandas

as

pd

s

=

pd.

Series

(

[

"A"

,

"B"

,

"C"

,

"A"

,

"B"

]

,

dtype

=

"category"

)

print

(

"Modified category names:"

)

s2

=

s.

cat

.

rename_categories

(

{

"A"

:

"Excellent"

,

"B"

:

"Good"

,

"C"

:

"Pass"

}

)

print

(

s2

)

print

(

)

Add a new category

print

(

"Added category:"

)

s3

=

s.

cat

.

add_categories

(

[

"D"

]

)

print

(

s3.

dtype

.

categories

.

tolist

(

)

)

print

(

)

Remove a category

print

(

"Removed category:"

)

s4

=

s.

cat

.

remove_categories

(

[

"C"

]

)

print

(

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

print

(

"High > Medium:"

,

s

"Center"

)

print

(

"Medium > Low:"

,

s

"Low"

)

print

(

)

Sorting

print

(

"After sorting:"

)

print

(

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

}

)

print

(

"User level distribution:"

)

print

(

users

[

"Level"

]

.

value_counts

(

)

.

sort_index

(

)

)

print

(

)

Group and count by level

print

(

"Statistics by level:"

)

print

(

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

print

(

f

"String type memory: {s_str.memory_usage(deep=True) / 1024 / 1024:.2f} MB"

)

print

(

f

"Categorical type memory: {s_cat.memory_usage(deep=True) / 1024 / 1024:.2f} MB"

)

print

(

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.