pandas-dev/pandas · #72081

BUG: ufunc with a pandas object as `where` recursed infinitely (GH#60611)

jbrockmendel · merged Nov 18, 202611 files · 247 + / 1 −
doc/source/whatsnew/v3.2.0.rst1 + / 0 −
@@ -547,6 +547,7 @@ Other - Bug in :meth:`DataFrame.query` and :meth:`DataFrame.eval` with ``engine="numexpr"`` raising ``AttributeError`` for some comparisons and ``in``/``not in`` checks whose operand is a math function or unary operator, e.g. ``abs(a) in [1, 2]`` (:issue:`31848`) - Bug in :meth:`Index.get_loc`, :meth:`Series.value_counts`, :meth:`Series.duplicated`, :meth:`Series.isin` and other object-dtype operations where a ``SystemExit`` raised by a custom ``__hash__`` or ``__eq__`` was silently suppressed (:issue:`57052`) - Bug in calling a generalized ufunc on a :class:`Series` raising ``AttributeError`` when it reduced ``object`` data to a single object pandas does not recognize as a scalar, e.g. ``shapely.geometrycollections`` returning a geometry (:issue:`71109`)+- Bug in calling a ufunc with a pandas object as ``where``, e.g. ``np.maximum(ser, 0, where=ser > 2)``, recursing infinitely; a :class:`Series` or :class:`DataFrame` ``where`` must now have the same labels as the inputs, and a ``where`` with missing values now raises instead of treating them as ``True`` (:issue:`60611`) - Bug in :func:`eval`, :meth:`DataFrame.eval`, and :meth:`DataFrame.query` raising on some ``datetime64`` and ``timedelta64`` operations, e.g. ``df.query("time > @now - @delta")``, and returning ``float32`` for a ``float32`` column times a ``np.timedelta64`` (:issue:`30729`, :issue:`52559`) - Bug in :meth:`DataFrame.eval` and :func:`eval` where assigning to a backtick-quoted name that is not a valid Python identifier, e.g. ``df.eval("`a-b` = a + b")``, created a column labeled ``BACKTICK_QUOTED_STRING_a_MINUS_b`` instead of ``"a-b"`` (:issue:`47699`) 
pandas/core/arraylike.py64 + / 1 −
@@ -19,7 +19,13 @@ from pandas._libs.ops_dispatch import maybe_dispatch_ufunc_to_dunder_op  from pandas.core.dtypes.cast import maybe_unbox_numpy_scalar-from pandas.core.dtypes.generic import ABCNDFrame+from pandas.core.dtypes.common import is_bool_dtype+from pandas.core.dtypes.generic import (+    ABCExtensionArray,+    ABCIndex,+    ABCNDFrame,+)+from pandas.core.dtypes.missing import isna  from pandas.core import roperator from pandas.core.construction import extract_array@@ -293,6 +299,15 @@ def array_ufunc(self, ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any)      cls = type(self) +    if kwargs.get("where") is self and not any(x is self for x in inputs):+        # numpy tries a subclass first; defer so a pandas input checks the labels+        if any(isinstance(x, NDFrame) for x in inputs):+            return NotImplemented++    result = dispatch_where_only_ufunc(self, ufunc, method, *inputs, **kwargs)+    if result is not NotImplemented:+        return result+     disallow_datetimelike_logical_ufunc(ufunc, inputs)      kwargs = _standardize_out_kwarg(**kwargs)@@ -411,6 +426,9 @@ def _reconstruct(result):             result = result.__finalize__(self)         return result +    if isinstance(kwargs.get("where"), ABCNDFrame):+        kwargs["where"] = _unbox_where(kwargs["where"], reconstruct_axes)+     if "out" in kwargs:         # e.g. test_multiindex_get_loc         result = dispatch_ufunc_with_out(self, ufunc, method, *inputs, **kwargs)@@ -477,6 +495,49 @@ def _standardize_out_kwarg(**kwargs) -> dict[str, Any]:     return kwargs  +def _unbox_where(where, axes: dict[str, Any]) -> np.ndarray:+    """+    Convert a Series or DataFrame passed as a ufunc's `where` to an ndarray.++    It must be labeled identically to the (aligned) inputs; we raise rather+    than guess between label-based and positional matching.+    """+    same_axes = where.ndim == len(axes) and all(+        ax.equals(other) for ax, other in zip(where.axes, axes.values(), strict=True)+    )+    if not same_axes:+        raise ValueError(+            "The ufunc 'where' argument must have the same axes as the aligned inputs"+        )+    return _where_to_ndarray(where)+++def _where_to_ndarray(where) -> np.ndarray:+    # checked for every dtype: np.putmask (the `out=` path) and a Categorical's+    #  to_numpy(dtype=bool) would both treat a missing value as True+    if isna(where).any(axis=None):+        raise ValueError("The ufunc 'where' argument cannot contain missing values")+    dtypes = where.dtypes if where.ndim == 2 else [where.dtype]+    if not all(is_bool_dtype(dtype) for dtype in dtypes):+        # left for numpy to validate; np.putmask, used with `out=`, is laxer+        return np.asarray(where)+    return where.to_numpy(dtype=bool)+++def dispatch_where_only_ufunc(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):+    """+    Handle a ufunc that reached `self` only through its `where` argument.++    numpy defers to a `where` that defines __array_ufunc__, so passing `self`+    on unchanged would recurse (GH#60611). As a mask, `self` has no say in the+    result type.+    """+    if kwargs.get("where") is not self or any(x is self for x in inputs):+        return NotImplemented+    kwargs["where"] = _where_to_ndarray(self)+    return getattr(ufunc, method)(*inputs, **kwargs)++ def dispatch_ufunc_with_out(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):     """     If we have an `out` keyword, then call the ufunc without `out` and then@@ -486,6 +547,8 @@ def dispatch_ufunc_with_out(self, ufunc: np.ufunc, method: str, *inputs, **kwarg     # Note: we assume _standardize_out_kwarg has already been called.     out = kwargs.pop("out")     where = kwargs.pop("where", None)+    if isinstance(where, (ABCNDFrame, ABCIndex, ABCExtensionArray)):+        where = _where_to_ndarray(where)      result = getattr(ufunc, method)(*inputs, **kwargs) 
pandas/core/arrays/arrow/array.py6 + / 0 −
@@ -1250,6 +1250,12 @@ def __arrow_array__(self, type=None):         return self._pa_array      def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):+        result = arraylike.dispatch_where_only_ufunc(+            self, ufunc, method, *inputs, **kwargs+        )+        if result is not NotImplemented:+            return result+         if (             not is_nan_na()             and type(self) is ArrowExtensionArray
pandas/core/arrays/base.py6 + / 0 −
@@ -3113,6 +3113,12 @@ def __array_function__(self, func, types, args, kwargs):             _IN_ARRAY_FUNCTION.reset(token)      def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):+        result = arraylike.dispatch_where_only_ufunc(+            self, ufunc, method, *inputs, **kwargs+        )+        if result is not NotImplemented:+            return result+         # the fallback at the end of this method np.asarray()s the values: M8/m8         #  survive to be truth-tested, the rest flatten to object         ops.disallow_datetimelike_logical_ufunc(ufunc, inputs)
pandas/core/arrays/categorical.py6 + / 0 −
@@ -1985,6 +1985,12 @@ def to_dense(self) -> ArrayLike:         return take_nd(self.categories._values, self._codes)      def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):+        result = arraylike.dispatch_where_only_ufunc(+            self, ufunc, method, *inputs, **kwargs+        )+        if result is not NotImplemented:+            return result+         # for binary ops, use our custom dunder methods         result = arraylike.maybe_dispatch_ufunc_to_dunder_op(             self, ufunc, method, *inputs, **kwargs
pandas/core/arrays/masked.py6 + / 0 −
@@ -885,6 +885,12 @@ def __array__(     _HANDLED_TYPES: tuple[type, ...]      def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):+        result = arraylike.dispatch_where_only_ufunc(+            self, ufunc, method, *inputs, **kwargs+        )+        if result is not NotImplemented:+            return result+         # For MaskedArray inputs, we apply the ufunc to ._data         # and mask the result. 
pandas/core/arrays/numpy_.py6 + / 0 −
@@ -255,6 +255,12 @@ def __array__(         return result      def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):+        result = arraylike.dispatch_where_only_ufunc(+            self, ufunc, method, *inputs, **kwargs+        )+        if result is not NotImplemented:+            return result+         # Lightly modified version of         # https://numpy.org/doc/stable/reference/generated/numpy.lib.mixins.NDArrayOperatorsMixin.html         # The primary modification is not boxing scalar return values
pandas/core/arrays/sparse/array.py6 + / 0 −
@@ -2835,6 +2835,12 @@ def argmin(self, skipna: bool = True) -> int:     _HANDLED_TYPES = (np.ndarray, numbers.Number)      def __array_ufunc__(self, ufunc: np.ufunc, method: str, *inputs, **kwargs):+        result = arraylike.dispatch_where_only_ufunc(+            self, ufunc, method, *inputs, **kwargs+        )+        if result is not NotImplemented:+            return result+         # this path never reaches ExtensionArray.__array_ufunc__, and a datetimelike         #  scalar is not in _HANDLED_TYPES, so this has to precede that loop         ops.disallow_datetimelike_logical_ufunc(ufunc, inputs)
pandas/core/indexes/base.py6 + / 0 −
@@ -983,6 +983,12 @@ def __array__(     def __array_ufunc__(         self, ufunc: np.ufunc, method: str_t, *inputs: Any, **kwargs: Any     ) -> Any:+        result = arraylike.dispatch_where_only_ufunc(+            self, ufunc, method, *inputs, **kwargs+        )+        if result is not NotImplemented:+            return result+         if any(isinstance(other, (ABCSeries, ABCDataFrame)) for other in inputs):             return NotImplemented 
pandas/tests/frame/test_ufunc.py27 + / 0 −
@@ -112,6 +112,33 @@ def test_binary_ufunc_out_pandas_object():     tm.assert_frame_equal(out, expected)  +# np.asarray would make "boolean" columns object dtype, which numpy rejects+@pytest.mark.filterwarnings("ignore:'where' used without 'out':UserWarning")+@pytest.mark.parametrize("dtype", ["bool", "boolean"])+def test_ufunc_where_pandas_object(dtype):+    # GH#60611 a DataFrame as `where` used to recurse infinitely+    df = pd.DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 5.0, 6.0]})+    result = np.maximum(df, 0, where=(df > 0).astype(dtype))+    tm.assert_frame_equal(result, df)++    out = np.full((3, 2), -1.0)+    result = np.maximum(df, 2.5, where=(df > 2).astype(dtype), out=out)+    expected = pd.DataFrame({"a": [-1.0, -1.0, 3.0], "b": [4.0, 5.0, 6.0]})+    tm.assert_frame_equal(result, expected)++    msg = "The ufunc 'where' argument must have the same axes as the aligned inputs"+    with pytest.raises(ValueError, match=msg):+        np.maximum(df, 0, where=df[["b", "a"]] > 0)+    with pytest.raises(ValueError, match=msg):+        np.maximum(df, 0, where=tm.SubclassedDataFrame(df.iloc[::-1] > 0), out=out)++    where = (df > 2).astype("boolean")+    where.iloc[0, 1] = pd.NA+    msg = "The ufunc 'where' argument cannot contain missing values"+    with pytest.raises(ValueError, match=msg):+        np.maximum(df, 2.5, where=where, out=out)++ @pytest.mark.parametrize("dtype_a", dtypes) @pytest.mark.parametrize("dtype_b", dtypes) def test_binary_input_aligns_columns(request, dtype_a, dtype_b):
pandas/tests/series/test_ufunc.py113 + / 0 −
@@ -280,6 +280,119 @@ def test_binary_ufunc_out_pandas_object():     tm.assert_series_equal(out, expected)  +@pytest.mark.filterwarnings("ignore:'where' used without 'out':UserWarning")+@pytest.mark.parametrize("box", [pd.Series, pd.Index, pd.array])+def test_ufunc_where_pandas_object(box):+    # GH#60611 a pandas object as `where` used to recurse infinitely+    ser = pd.Series([-3.0, 4.0, 1.0], name="a")+    mask = np.array([False, True, True])+    expected = pd.Series([4.0, 2.0], index=[1, 2], name="a")++    # positions where mask is False are left uninitialized+    result = np.maximum(ser, 2.0, where=box(mask))+    tm.assert_series_equal(result[mask], expected)++    result = np.maximum(ser, 2.0, where=box(mask), out=np.full(3, -1.0))+    tm.assert_series_equal(result, pd.Series([-1.0, 4.0, 2.0], name="a"))+++where_boxes = [+    pd.Series,+    pd.Index,+    pd.array,+    pd.Categorical,+    pd.arrays.SparseArray,+    pd.arrays.NumpyExtensionArray,+    pytest.param(+        lambda x: pd.array(x, dtype="bool[pyarrow]"),+        marks=td.skip_if_no("pyarrow"),+        id="arrow",+    ),+]+++@pytest.mark.filterwarnings("ignore:'where' used without 'out':UserWarning")+@pytest.mark.parametrize("box", where_boxes)+@pytest.mark.parametrize(+    "values",+    [+        np.array([-3.0, 4.0, 1.0]),+        pd.Index([-3.0, 4.0, 1.0]),+        pd.Index(pd.array([-3, 4, 1], dtype="Int64")),+        pd.array([-3.0, 4.0, 1.0], dtype="Float64"),+        pd.arrays.NumpyExtensionArray(np.array([-3.0, 4.0, 1.0])),+        pd.array(pd.to_timedelta([-3, 4, 1], unit="s")),+    ],+    ids=type,+)+def test_ufunc_where_pandas_object_only_where(values, box):+    # GH#60611 a pandas `where` only masks; the inputs decide the result type+    mask = np.array([False, True, True])+    result = np.negative(values, where=box(mask))+    expected = np.negative(values, where=mask)+    assert type(result) is type(expected)+    tm.assert_equal(result[mask], expected[mask])+++@pytest.mark.parametrize("box", where_boxes)+def test_ufunc_where_pandas_object_only_where_out(box):+    # GH#60611 like numpy, the result is `out` itself+    out = np.full(3, np.nan)+    where = box(np.array([False, True, True]))+    result = np.negative(np.array([-3.0, 4.0, 1.0]), where=where, out=out)+    assert result is out+    tm.assert_numpy_array_equal(out, np.array([np.nan, -4.0, -1.0]))+++def test_ufunc_where_misaligned_raises():+    # GH#60611 we don't guess whether to match `where` by label or position+    ser = pd.Series([1.0, 2.0, 3.0])+    mask = pd.Series([True, False, False], index=[2, 1, 0])+    msg = "The ufunc 'where' argument must have the same axes as the aligned inputs"+    with pytest.raises(ValueError, match=msg):+        np.maximum(ser, 10.0, where=mask, out=np.zeros(3))+    with pytest.raises(ValueError, match=msg):+        np.maximum(ser, 10.0, where=mask.iloc[:2])+    # numpy tries a subclass's __array_ufunc__ first+    with pytest.raises(ValueError, match=msg):+        np.maximum(ser, 10.0, where=tm.SubclassedSeries(mask), out=np.zeros(3))+++@pytest.mark.parametrize(+    "where",+    [+        pd.Series(pd.array([True, None, False])),+        pd.Series([True, None, False], dtype=object),+        pd.Index(pd.array([True, None, False])),+        pd.array([True, None, False]),+        pd.Categorical([True, None, False]),+        pytest.param(+            lambda: pd.array([True, None, False], dtype="bool[pyarrow]"),+            marks=td.skip_if_no("pyarrow"),+            id="arrow",+        ),+    ],+    ids=type,+)+@pytest.mark.parametrize(+    "values",+    [+        np.array([1.0, 2.0, 3.0]),+        pd.Series([1.0, 2.0, 3.0]),+        pd.Index([1.0, 2.0, 3.0]),+        pd.array([1.0, 2.0, 3.0], dtype="Float64"),+    ],+    ids=type,+)+def test_ufunc_where_missing_raises(values, where):+    # GH#60611 a pandas input with `out=` used to treat a missing value as True+    if callable(where):+        where = where()+    msg = "The ufunc 'where' argument cannot contain missing values"+    with pytest.raises(ValueError, match=msg):+        np.negative(values, where=where, out=np.zeros(3))++ def test_object_series_ok():     class Dummy:         def __init__(self, value) -> None: