Skip to content

Commit

Permalink
Method.len (#237)
Browse files Browse the repository at this point in the history
  • Loading branch information
brentomagic authored May 31, 2024
1 parent 16035ee commit cfd5c27
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions narwhals/expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -2356,7 +2356,39 @@ def all() -> Expr:

def len() -> Expr:
"""
Instantiate an expression representing the length of a dataframe, similar to `polars.len`.
Return the number of rows.
Arguments:
*columns: Name(s) of the columns to use in the aggregation function.
Examples:
>>> import polars as pl
>>> import pandas as pd
>>> import narwhals as nw
>>> df_pd = pd.DataFrame({'a': [1, 2], 'b': [5, 10]})
>>> df_pl = pl.DataFrame({'a': [1, 2], 'b': [5, 10]})
Let's define a dataframe-agnostic function:
>>> def func(df_any):
... df = nw.from_native(df_any)
... df = df.select(nw.len())
... return nw.to_native(df)
We can then pass either pandas or Polars to `func`:
>>> func(df_pd)
len
0 2
>>> func(df_pl)
shape: (1, 1)
┌─────┐
│ len │
│ --- │
│ u32 │
╞═════╡
│ 2 │
└─────┘
"""

def func(plx: Any) -> Any:
Expand All @@ -2365,7 +2397,7 @@ def func(plx: Any) -> Any:
and (pl := get_polars()) is not None
and parse_version(pl.__version__) < parse_version("0.20.4")
): # pragma: no cover
return plx.count()
return plx.count().alias("len")
return plx.len()

return Expr(func)
Expand Down

0 comments on commit cfd5c27

Please sign in to comment.