narwhals.Series.cat
get_categories()
Get unique categories from column.
Examples:
Let's create some series:
>>> import pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> from narwhals.typing import IntoSeriesT
>>> data = ["apple", "mango", "mango"]
>>> s_pd = pd.Series(data, dtype="category")
>>> s_pl = pl.Series(data, dtype=pl.Categorical)
We define a dataframe-agnostic function to get unique categories from column 'fruits':
>>> def my_library_agnostic_function(s_native: IntoSeriesT) -> IntoSeriesT:
... s = nw.from_native(s_native, series_only=True)
... return s.cat.get_categories().to_native()
We can then pass either pandas or Polars to func
:
>>> my_library_agnostic_function(s_pd)
0 apple
1 mango
dtype: object
>>> my_library_agnostic_function(s_pl)
shape: (2,)
Series: '' [str]
[
"apple"
"mango"
]