From ef5c7b4e7c3dedec4811b7fc80d44951028b0d67 Mon Sep 17 00:00:00 2001 From: Arthur Lacote Date: Fri, 13 Nov 2026 17:24:27 +0100 Subject: [PATCH] BUG: fix weighted nanquantile with 1-D weights Give a zero weight to the NaNs and use the weighted quantile, instead of a separate code path that failed to broadcast 1-D weights (gh-29709). A slice left with only NaNs or zero weights gives NaN and a RuntimeWarning. Refresh of gh-30066 on the current main. Co-Authored-By: Claude Fable 5.2 --- numpy/lib/_function_base_impl.py | 13 +++- numpy/lib/_nanfunctions_impl.py | 73 +++++++++--------- numpy/lib/tests/test_nanfunctions.py | 110 ++++++++++++++++++++++----- 3 files changed, 136 insertions(+), 60 deletions(-) diff --git a/numpy/lib/_function_base_impl.py b/numpy/lib/_function_base_impl.py index 116a26457abe..49acc4bd815f 100644 --- a/numpy/lib/_function_base_impl.py +++ b/numpy/lib/_function_base_impl.py @@ -4528,7 +4528,8 @@ def _quantile_unchecked(a, method="linear", keepdims=False, weights=None, - weak_q=False): + weak_q=False, + ignore_nans=False): """Assumes that q is in [0, 1], and is an ndarray""" return _ureduce(a, func=_quantile_ureduce_func, @@ -4539,7 +4540,8 @@ def _quantile_unchecked(a, out=out, overwrite_input=overwrite_input, method=method, - weak_q=weak_q) + weak_q=weak_q, + ignore_nans=ignore_nans) def _quantile_is_valid(q): @@ -4672,6 +4674,7 @@ def _quantile_ureduce_func( overwrite_input: bool = False, method: str = "linear", weak_q: bool = False, + ignore_nans: bool = False, ) -> np.ndarray: if q.ndim > 2: # The code below works fine for nd, but it might not have useful @@ -4699,7 +4702,8 @@ def _quantile_ureduce_func( method=method, out=out, weights=wgt, - weak_q=weak_q) + weak_q=weak_q, + ignore_nans=ignore_nans) return result @@ -4746,6 +4750,7 @@ def _quantile( out: np.ndarray | None = None, weights: "np.typing.ArrayLike | None" = None, weak_q: bool = False, + ignore_nans: bool = False, ) -> np.ndarray: """ Private function that doesn't support extended axis or keepdims. @@ -4766,7 +4771,7 @@ def _quantile( # axis being sampled from `arr` to be last. if axis != 0: # But moveaxis is slow, so only call it if necessary. arr = np.moveaxis(arr, axis, destination=0) - supports_nans = ( + supports_nans = (not ignore_nans) and ( np.issubdtype(arr.dtype, np.inexact) or arr.dtype.kind in 'Mm' ) diff --git a/numpy/lib/_nanfunctions_impl.py b/numpy/lib/_nanfunctions_impl.py index b262329afbbe..d86debb1b63e 100644 --- a/numpy/lib/_nanfunctions_impl.py +++ b/numpy/lib/_nanfunctions_impl.py @@ -1590,10 +1590,39 @@ def _nanquantile_unchecked( # so deal them upfront if a.size == 0: return np.nanmean(a, axis, out=out, keepdims=keepdims) + if weights is not None: + # Give a zero weight to the NaNs and use the weighted quantile, which + # then ignores them. + if a.dtype == object: + # object arrays do not support `isnan` (gh-9009), so make a guess + isnan = np.not_equal(a, a, dtype=bool) + else: + isnan = np.isnan(a) + if isnan.any(): + weights = np.where(isnan, 0, weights) + + # A slice with only NaNs or zero weights has no quantile: the result + # is NaN, as for an all-NaN slice without weights. + empty_slices = np.all(weights == 0, axis=axis, keepdims=True) + if empty_slices.any(): + warnings.warn("Slice encountered with all NaN or 0-weight samples", + RuntimeWarning, stacklevel=3) + # set the values to NaN and the weights to 1 for those slices + weights = weights + empty_slices + if a.dtype.kind in "mM": + nan = np.array("NaT", dtype=a.dtype) + else: + nan = np.nan + a = np.where(empty_slices, nan, a) + + return fnb._quantile_unchecked( + a, q, axis, out, overwrite_input, method, keepdims, + weights=weights, weak_q=weak_q, ignore_nans=True, + ) + return fnb._ureduce(a, func=_nanquantile_ureduce_func, q=q, - weights=weights, keepdims=keepdims, axis=axis, out=out, @@ -1605,7 +1634,6 @@ def _nanquantile_unchecked( def _nanquantile_ureduce_func( a: np.ndarray, q: np.ndarray, - weights: np.ndarray, axis: int | None = None, out=None, overwrite_input: bool = False, @@ -1619,40 +1647,17 @@ def _nanquantile_ureduce_func( """ if axis is None or a.ndim == 1: part = a.ravel() - wgt = None if weights is None else weights.ravel() - result = _nanquantile_1d(part, q, overwrite_input, method, - weights=wgt, weak_q=weak_q) - # Note that this code could try to fill in `out` right away - elif weights is None: + result = _nanquantile_1d(part, q, overwrite_input, method, weak_q) + else: + # Note that this code could try to fill in `out` right away result = np.apply_along_axis(_nanquantile_1d, axis, a, q, - overwrite_input, method, weights, weak_q) + overwrite_input, method, weak_q) # apply_along_axis fills in collapsed axis with results. # Move those axes to the beginning to match percentile's # convention. if q.ndim != 0: from_ax = [axis + i for i in range(q.ndim)] result = np.moveaxis(result, from_ax, list(range(q.ndim))) - else: - # We need to apply along axis over 2 arrays, a and weights. - # move operation axes to end for simplicity: - a = np.moveaxis(a, axis, -1) - if weights is not None: - weights = np.moveaxis(weights, axis, -1) - if out is not None: - result = out - else: - # weights are limited to `inverted_cdf` so the result dtype - # is known to be identical to that of `a` here: - result = np.empty_like(a, shape=q.shape + a.shape[:-1]) - - for ii in np.ndindex(a.shape[:-1]): - result[(...,) + ii] = _nanquantile_1d( - a[ii], q, weights=weights[ii], - overwrite_input=overwrite_input, method=method, - weak_q=weak_q, - ) - # This path dealt with `out` already... - return result if out is not None: out[...] = result @@ -1660,27 +1665,23 @@ def _nanquantile_ureduce_func( def _nanquantile_1d( - arr1d, q, overwrite_input=False, method="linear", weights=None, - weak_q=False, + arr1d, q, overwrite_input=False, method="linear", weak_q=False, ): """ Private function for rank 1 arrays. Compute quantile ignoring NaNs. See nanpercentile for parameter usage """ - # TODO: What to do when arr1d = [1, np.nan] and weights = [0, 1]? - arr1d, weights, overwrite_input = _remove_nan_1d(arr1d, - second_arr1d=weights, overwrite_input=overwrite_input) + arr1d, _, overwrite_input = _remove_nan_1d( + arr1d, overwrite_input=overwrite_input) if arr1d.size == 0: # Use the quantile implementation to preserve its output dtype. arr1d = np.full(1, np.nan, dtype=arr1d.dtype) - weights = None return fnb._quantile_unchecked( arr1d, q, overwrite_input=overwrite_input, method=method, - weights=weights, weak_q=weak_q, ) diff --git a/numpy/lib/tests/test_nanfunctions.py b/numpy/lib/tests/test_nanfunctions.py index ee86c3ea28fb..f9a15e250f50 100644 --- a/numpy/lib/tests/test_nanfunctions.py +++ b/numpy/lib/tests/test_nanfunctions.py @@ -1108,19 +1108,37 @@ def test_float_special(self): class TestNanFunctions_Percentile: + @staticmethod + def _get_w_args(mat, weighted, axis): + if weighted is False: + return {} + if weighted == "1d" and not isinstance(axis, int): + return {} + w_args = {"method": "inverted_cdf"} + if weighted == "1d": + w_args["weights"] = np.ones(mat.shape[axis]) + else: + w_args["weights"] = np.ones_like(mat) + return w_args + def test_mutation(self): # Check that passed array is not modified. ndat = _ndat.copy() np.nanpercentile(ndat, 30) assert_equal(ndat, _ndat) - def test_keepdims(self): - mat = np.eye(3) + @pytest.mark.parametrize("weighted", [False, "1d", "2d"]) + def test_keepdims(self, weighted): + mat = np.arange(20).reshape((4, 5)) for axis in [None, 0, 1]: - tgt = np.percentile(mat, 70, axis=axis, out=None, - overwrite_input=False) - res = np.nanpercentile(mat, 70, axis=axis, out=None, - overwrite_input=False) + tgt = np.percentile( + mat, 70, axis=axis, out=None, overwrite_input=False, + **self._get_w_args(mat, weighted, axis) + ) + res = np.nanpercentile( + mat, 70, axis=axis, out=None, overwrite_input=False, + **self._get_w_args(mat, weighted, axis) + ) assert_(res.ndim == tgt.ndim) d = np.ones((3, 5, 7, 11)) @@ -1174,33 +1192,32 @@ def test_keepdims_out(self, q, axis): assert result is out assert_equal(result.shape, shape_out) - @pytest.mark.parametrize("weighted", [False, True]) + @pytest.mark.parametrize("weighted", [False, "1d", "2d"]) def test_out(self, weighted): mat = np.random.rand(3, 3) nan_mat = np.insert(mat, [0, 2], np.nan, axis=1) resout = np.zeros(3) - if weighted: - w_args = {"weights": np.ones_like(mat), "method": "inverted_cdf"} - nan_w_args = { - "weights": np.ones_like(nan_mat), "method": "inverted_cdf" - } - else: - w_args = {} - nan_w_args = {} - tgt = np.percentile(mat, 42, axis=1, **w_args) - res = np.nanpercentile(nan_mat, 42, axis=1, out=resout, **nan_w_args) + tgt = np.percentile(mat, 42, axis=1, + **self._get_w_args(mat, weighted, axis=1)) + res = np.nanpercentile(nan_mat, 42, axis=1, out=resout, + **self._get_w_args(nan_mat, weighted, axis=1)) assert_almost_equal(res, resout) assert_almost_equal(res, tgt) # 0-d output: resout = np.zeros(()) - tgt = np.percentile(mat, 42, axis=None, **w_args) + tgt = np.percentile(mat, 42, axis=None, + **self._get_w_args(mat, weighted, axis=None)) res = np.nanpercentile( - nan_mat, 42, axis=None, out=resout, **nan_w_args + nan_mat, 42, axis=None, out=resout, + **self._get_w_args(nan_mat, weighted, axis=None) ) assert_almost_equal(res, resout) assert_almost_equal(res, tgt) + tgt = np.percentile(mat, 42, axis=(0, 1), + **self._get_w_args(mat, weighted, axis=(0, 1))) res = np.nanpercentile( - nan_mat, 42, axis=(0, 1), out=resout, **nan_w_args + nan_mat, 42, axis=(0, 1), out=resout, + **self._get_w_args(nan_mat, weighted, axis=(0, 1)) ) assert_almost_equal(res, resout) assert_almost_equal(res, tgt) @@ -1370,6 +1387,59 @@ def test_nan_value_with_weight_ndim(self, axis): assert res is out assert_equal(out, p_expected) + @pytest.mark.parametrize("axis", [0, 1]) + def test_1d_weights_with_nans(self, axis): + # gh-29709: 1-D weights raised an IndexError + rng = np.random.default_rng(0) + x = rng.random((5, 4)) + x[1, 2] = x[3, 0] = np.nan + w = rng.random(x.shape[axis]) + q = [100 / 3, 200 / 3] + w_full = np.broadcast_to(w if axis == 1 else w[:, None], x.shape) + expected = np.nanpercentile( + x, q, axis=axis, weights=w_full, method="inverted_cdf") + res = np.nanpercentile( + x, q, axis=axis, weights=w, method="inverted_cdf") + assert_equal(res, expected) + # each slice matches the quantile of its non-NaN values + for i, xi in enumerate(np.moveaxis(x, axis, -1)): + keep = ~np.isnan(xi) + assert_equal(res[:, i], np.percentile( + xi[keep], q, weights=w[keep], method="inverted_cdf")) + + @pytest.mark.parametrize("x, w", [ + ([1., 2.], [0., 0.]), + ([1., np.nan], [0., 1.]), + ([np.nan, np.nan], [1., 1.]), + ]) + def test_weights_all_nan_or_zero(self, x, w): + # no value is left: NaN and a warning, as for an all-NaN slice + with pytest.warns(RuntimeWarning, match="all NaN or 0-weight"): + res = np.nanpercentile(x, 50, weights=w, method="inverted_cdf") + assert np.isnan(res) + + def test_weights_all_nan_or_zero_ndim(self): + x = np.array([[1., 2., 3.], [4., np.nan, 6.], [np.nan, np.nan, 9.]]) + w = np.array([[0., 0., 0.], [1., 1., 0.], [1., 1., 1.]]) + with pytest.warns(RuntimeWarning, match="all NaN or 0-weight"): + res = np.nanpercentile( + x, 50, axis=1, weights=w, method="inverted_cdf") + assert_equal(res, [np.nan, 4., 9.]) + # the inputs are not modified + assert_equal(x[0], [1., 2., 3.]) + assert_equal(w[0], [0., 0., 0.]) + + def test_weights_all_nat_or_zero(self): + x = np.array(["2020-01-01", "NaT", "2020-01-03"], dtype="M8[D]") + res = np.nanpercentile( + x, 50, weights=[1, 5, 0], method="inverted_cdf") + assert_equal(res, x[0]) + with pytest.warns(RuntimeWarning, match="all NaN or 0-weight"): + res = np.nanpercentile( + x, 50, weights=[0, 5, 0], method="inverted_cdf") + assert res.dtype == x.dtype + assert np.isnat(res) + class TestNanFunctions_Quantile: # most of this is already tested by TestPercentile