Skip to content

Commit

Permalink
Merge pull request #87 from ugohuche/is_null
Browse files Browse the repository at this point in the history
Added docstring for Expr.is_null
  • Loading branch information
MarcoGorelli authored May 6, 2024
2 parents 7862dc1 + c2d8320 commit a3d20aa
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions narwhals/expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,60 @@ def filter(self, other: Any) -> Expr:
)

def is_null(self) -> Expr:
"""
Returns a boolean Series indicating which values are null.
Examples:
>>> import pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>> df_pd = pd.DataFrame(
... {
... 'a': [2, 4, None, 3, 5],
... 'b': [2.0, 4.0, float("nan"), 3.0, 5.0]
... }
... )
>>> df_pl = pl.DataFrame(
... {
... 'a': [2, 4, None, 3, 5],
... 'b': [2.0, 4.0, float("nan"), 3.0, 5.0]
... }
... )
Let's define a dataframe-agnostic function:
>>> def func(df_any):
... df = nw.from_native(df_any)
... df = df.with_columns(
... a_is_null = nw.col('a').is_null(),
... b_is_null = nw.col('b').is_null()
... )
... return nw.to_native(df)
We can then pass either pandas or Polars to `func`:
>>> func(df_pd)
a b a_is_null b_is_null
0 2.0 2.0 False False
1 4.0 4.0 False False
2 NaN NaN True True
3 3.0 3.0 False False
4 5.0 5.0 False False
>>> func(df_pl) # nan != null for polars
shape: (5, 4)
┌──────┬─────┬───────────┬───────────┐
│ a ┆ b ┆ a_is_null ┆ b_is_null │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ bool ┆ bool │
╞══════╪═════╪═══════════╪═══════════╡
│ 2 ┆ 2.0 ┆ false ┆ false │
│ 4 ┆ 4.0 ┆ false ┆ false │
│ null ┆ NaN ┆ true ┆ false │
│ 3 ┆ 3.0 ┆ false ┆ false │
│ 5 ┆ 5.0 ┆ false ┆ false │
└──────┴─────┴───────────┴───────────┘
"""
return self.__class__(lambda plx: self._call(plx).is_null())

# --- partial reduction ---
Expand Down

0 comments on commit a3d20aa

Please sign in to comment.