Skip to content

Commit

Permalink
Merge pull request #99 from brentomagic/main
Browse files Browse the repository at this point in the history
unique() and n_unique() docsrings
  • Loading branch information
MarcoGorelli authored May 7, 2024
2 parents 93d262e + d19c77e commit e8ea8b8
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions narwhals/expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,9 +454,77 @@ def max(self) -> Expr:
return self.__class__(lambda plx: self._call(plx).max())

def n_unique(self) -> Expr:
"""
Returns count of unique values
Examples:
>>> import polars as pl
>>> import pandas as pd
>>> import narwhals as nw
>>> df_pd = pd.DataFrame({'a': [1, 2, 3, 4, 5], 'b': [1, 1, 3, 3, 5]})
>>> df_pl = pl.DataFrame({'a': [1, 2, 3, 4, 5], 'b': [1, 1, 3, 3, 5]})
Let's define a dataframe-agnostic function:
>>> def func(df_any):
... df = nw.from_native(df_any)
... df = df.select(nw.col('a', 'b').n_unique())
... return nw.to_native(df)
We can then pass either pandas or Polars to `func`:
>>> func(df_pd)
a b
0 5 3
>>> func(df_pl)
shape: (1, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞═════╪═════╡
│ 5 ┆ 3 │
└─────┴─────┘
"""
return self.__class__(lambda plx: self._call(plx).n_unique())

def unique(self) -> Expr:
"""
Returns unique values
Examples:
>>> import polars as pl
>>> import pandas as pd
>>> import narwhals as nw
>>> df_pd = pd.DataFrame({'a': [1, 1, 3, 5, 5], 'b': [2, 4, 4, 6, 6]})
>>> df_pl = pl.DataFrame({'a': [1, 1, 3, 5, 5], 'b': [2, 4, 4, 6, 6]})
Let's define a dataframe-agnostic function:
>>> def func(df_any):
... df = nw.from_native(df_any)
... df = df.select(nw.col('a', 'b').unique())
... return nw.to_native(df)
We can then pass either pandas or Polars to `func`:
>>> func(df_pd)
a b
0 1 2
1 3 4
2 5 6
>>> func(df_pl)
shape: (3, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 2 │
│ 3 ┆ 4 │
│ 5 ┆ 6 │
└─────┴─────┘
"""
return self.__class__(lambda plx: self._call(plx).unique())

def sort(self, *, descending: bool = False) -> Expr:
Expand Down

0 comments on commit e8ea8b8

Please sign in to comment.