Skip to content

Commit 6aa1413

Browse files
authored
fix: allow for fill_null with aggregate expression (#3105)
* fix: allow for `fill_null` with aggregate expression * preserve str_as_lit=True * extra test
1 parent 2af3e8d commit 6aa1413

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

narwhals/expr.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1192,10 +1192,14 @@ def fill_null(
11921192
raise ValueError(msg)
11931193

11941194
return self.__class__(
1195-
lambda plx: self._to_compliant_expr(plx).fill_null(
1196-
value=plx.parse_into_expr(value, str_as_lit=True),
1197-
strategy=strategy,
1198-
limit=limit,
1195+
lambda plx: apply_n_ary_operation(
1196+
plx,
1197+
lambda *exprs: exprs[0].fill_null(
1198+
exprs[1], strategy=strategy, limit=limit
1199+
),
1200+
self,
1201+
value,
1202+
str_as_lit=True,
11991203
),
12001204
self._metadata.with_orderable_window()
12011205
if strategy is not None

tests/expr_and_series/fill_null_test.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,17 @@ def test_fill_null(constructor: Constructor) -> None:
3333
assert_equal_data(result, expected)
3434

3535

36+
def test_fill_null_w_aggregate(constructor: Constructor) -> None:
37+
data = {"a": [0.5, None, 2.0, 3.0, 4.5], "b": ["xx", "yy", "zz", None, "yy"]}
38+
df = nw.from_native(constructor(data))
39+
40+
result = df.select(
41+
nw.col("a").fill_null(nw.col("a").mean()), nw.col("b").fill_null("a")
42+
)
43+
expected = {"a": [0.5, 2.5, 2.0, 3.0, 4.5], "b": ["xx", "yy", "zz", "a", "yy"]}
44+
assert_equal_data(result, expected)
45+
46+
3647
def test_fill_null_pandas_downcast() -> None:
3748
pytest.importorskip("pandas")
3849
import pandas as pd

0 commit comments

Comments
 (0)