Michael Dorner
Michael Dorner

Reputation: 20125

How to get the category of a value in pandas

I wonder how I query and get the the category for a given value

For example, with the following code I map the four strings to four categories

cat_type = pd.api.types.CategoricalDtype(categories=['c1', 'c2', 'c3', 'c4'])

Now I want to query and get the category for another value, something like

cat_for_c1 = cat_type.<somehting>('c1') 

where as cat_for_c1 represents the category not the string value. It seems that there is no <something> according to the documentation.

Is it possible otherwise?

Upvotes: 1

Views: 285

Answers (1)

Laurent
Laurent

Reputation: 13458

get_indexer could be what you are looking for:

print(cat_type.categories.get_indexer(["c3"])[0])  # 2

print(cat_type.categories.get_indexer(["c5"])[0])  # -1

Upvotes: 0

Related Questions