Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: split namespaces out from expr and series #1782

Merged
merged 3 commits into from
Jan 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2,695 changes: 5 additions & 2,690 deletions narwhals/expr.py

Large diffs are not rendered by default.

66 changes: 66 additions & 0 deletions narwhals/expr_cat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from __future__ import annotations

from typing import TYPE_CHECKING
from typing import Generic
from typing import TypeVar

if TYPE_CHECKING:
from typing_extensions import Self

from narwhals.expr import Expr

ExprT = TypeVar("ExprT", bound="Expr")


class ExprCatNamespace(Generic[ExprT]):
def __init__(self: Self, expr: ExprT) -> None:
self._expr = expr

def get_categories(self: Self) -> ExprT:
"""Get unique categories from column.

Returns:
A new expression.

Examples:
Let's create some dataframes:

>>> import pandas as pd
>>> import polars as pl
>>> import pyarrow as pa
>>> import narwhals as nw
>>> from narwhals.typing import IntoFrameT
>>>
>>> data = {"fruits": ["apple", "mango", "mango"]}
>>> df_pd = pd.DataFrame(data, dtype="category")
>>> df_pl = pl.DataFrame(data, schema={"fruits": pl.Categorical})

We define a dataframe-agnostic function to get unique categories
from column 'fruits':

>>> def agnostic_cat_get_categories(df_native: IntoFrameT) -> IntoFrameT:
... df = nw.from_native(df_native)
... return df.select(nw.col("fruits").cat.get_categories()).to_native()

We can then pass any supported library such as pandas or Polars to
`agnostic_cat_get_categories`:

>>> agnostic_cat_get_categories(df_pd)
fruits
0 apple
1 mango

>>> agnostic_cat_get_categories(df_pl)
shape: (2, 1)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ fruits β”‚
β”‚ --- β”‚
β”‚ str β”‚
β•žβ•β•β•β•β•β•β•β•β•‘
β”‚ apple β”‚
β”‚ mango β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜
"""
return self._expr.__class__(
lambda plx: self._expr._to_compliant_expr(plx).cat.get_categories()
)
Loading
Loading