Skip to content

Commit 13216f7

Browse files
authored
fix: pyarrow when/then with nulls (#3502)
1 parent c4ff5e7 commit 13216f7

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

narwhals/_arrow/namespace.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,4 +252,4 @@ def _if_then_else(
252252
otherwise: ChunkedArrayAny | None = None,
253253
) -> ChunkedArrayAny:
254254
otherwise = pa.nulls(len(when), then.type) if otherwise is None else otherwise
255-
return pc.if_else(when, then, otherwise)
255+
return pc.if_else(when.fill_null(pa.scalar(False)), then, otherwise)

tests/expr_and_series/when_test.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,3 +227,13 @@ def test_when_then_empty(constructor: Constructor) -> None:
227227
result = df.with_columns(nw.when(nw.col("a") == 1).then(nw.lit(1)).alias("new_col"))
228228
expected: dict[str, Any] = {"a": [], "new_col": []}
229229
assert_equal_data(result, expected)
230+
231+
232+
def test_when_chain_with_nulls(constructor: Constructor) -> None:
233+
df = nw.from_native(constructor({"a": [1, None, 3, None, 5]}))
234+
235+
result = df.select(nw.when(nw.col("a") == 1).then(10).otherwise(99).alias("result"))
236+
237+
# Null values don't match any condition, so they get otherwise value
238+
expected = {"result": [10, 99, 99, 99, 99]}
239+
assert_equal_data(result, expected)

0 commit comments

Comments
 (0)