diff --git a/narwhals/expression.py b/narwhals/expression.py index 7641c58b0..1e5f53a38 100644 --- a/narwhals/expression.py +++ b/narwhals/expression.py @@ -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: @@ -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)