Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/narwhals/_arrow/namespace.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,11 @@ def func(df: ArrowDataFrame) -> list[ArrowSeries]:
expr_results = tuple(chain.from_iterable(expr(df) for expr in exprs))
series = [s.fill_null(0, strategy=None, limit=None) for s in expr_results]
non_na = [1 - s.is_null().cast(int_64) for s in expr_results]
return [reduce(operator.add, series) / reduce(operator.add, non_na)]
count = reduce(operator.add, non_na)
mean = reduce(operator.add, series) / count
# A row where every input is null has a count of 0: return null, not 0/0 = NaN.
native = pc.if_else((count == 0).native, None, mean.native)
return [mean._with_native(native, preserve_broadcast=True)]

return self._expr._from_callable(
func=func,
Expand Down
2 changes: 1 addition & 1 deletion src/narwhals/_duckdb/namespace.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def func(cols: Iterable[Expression]) -> Expression:
count = reduce(
operator.add, (col.isnotnull().cast(duckdb_dtypes.BIGINT) for col in cols)
)
return total / count
return when(count > lit(0), total / count)

return self._expr._from_elementwise_horizontal_op(func, *exprs)

Expand Down
2 changes: 1 addition & 1 deletion src/narwhals/_ibis/namespace.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def func(cols: Iterable[ir.Value]) -> ir.Value:
for col in cols
),
)
return numerator / denominator
return numerator / denominator.nullif(lit(0))

return self._expr._from_elementwise_horizontal_op(func, *exprs)

Expand Down
2 changes: 1 addition & 1 deletion src/narwhals/_spark_like/namespace.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ def func(cols: Iterable[Column]) -> Column:
operator.add,
(col.isNotNull().cast(self._native_dtypes.IntegerType()) for col in cols),
)
return true_divide(F, numerator, denominator)
return F.when(denominator > F.lit(0), true_divide(F, numerator, denominator))

return self._expr._from_elementwise_horizontal_op(func, *exprs)

Expand Down
10 changes: 10 additions & 0 deletions tests/expr_and_series/mean_horizontal_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,13 @@ def test_meanh_all(constructor: Constructor) -> None:
result = df.select(c=nw.mean_horizontal(nw.all()))
expected = {"c": [6, 12, 18]}
assert_equal_data(result, expected)


def test_meanh_all_null_row_is_null(constructor: Constructor) -> None:
data = {"a": [1.0, None], "b": [3.0, None]}
df = nw.from_native(constructor(data))
result = df.select(mean=nw.mean_horizontal("a", "b")).select(
nw.col("mean"), is_null=nw.col("mean").is_null()
)
expected = {"mean": [2.0, None], "is_null": [False, True]}
assert_equal_data(result, expected)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we extend this a bit?

  • an integer case, since that takes a different division path on several backends;
  • a check that the output is still Float64 when every row is null, as in Polars.

This needs import pytest at the top of the file. The filter is there to get an all-null column that keeps its dtype: building all-None columns directly fails on Ibis.

Suggested change
assert_equal_data(result, expected)
@pytest.mark.parametrize(
"data", [{"a": [1.0, None], "b": [3.0, None]}, {"a": [1, None], "b": [3, None]}]
)
def test_meanh_all_null_row_is_null(
constructor: Constructor, data: dict[str, list[float | None]]
) -> None:
df = nw.from_native(constructor(data))
mean = nw.mean_horizontal("a", "b")
result = df.select(mean=mean, is_null=mean.is_null())
expected = {"mean": [2.0, None], "is_null": [False, True]}
assert_equal_data(result, expected)
result = df.filter(nw.col("a").is_null()).select(mean=mean)
assert result.collect_schema() == {"mean": nw.Float64()}