pandas-dev/pandas · #72083

BUG: cut with nullable/pyarrow integers above 2**53 (GH#31389)

jbrockmendel · merged Nov 15, 20263 files · 98 + / 7 −
doc/source/whatsnew/v3.2.0.rst1 + / 0 −
@@ -454,6 +454,7 @@ Reshaping - Bug in :func:`concat` and the :class:`DataFrame` constructor losing the ``freq`` of a :class:`DatetimeIndex` or :class:`TimedeltaIndex` depending on the order of the inputs (:issue:`64253`) - Bug in :func:`concat` raising ``ArrowInvalid`` when casting integers exceeding ``2**53`` to a PyArrow float dtype, e.g. ``int64[pyarrow]`` with ``uint64[pyarrow]``; these now round as with NumPy dtypes (:issue:`58819`) - Bug in :func:`concat` raising ``ValueError`` when tuple ``keys`` contain a missing value such as ``None`` (:issue:`57993`)+- Bug in :func:`cut` with nullable or PyArrow integer data placing values above ``2**53`` in the wrong bin (:issue:`31389`) - Bug in :func:`merge_asof` with ``right_index=True`` and an empty ``left`` returning the index of ``right`` instead of ``left`` (:issue:`41171`) - Bug in :func:`merge` raising ``ValueError`` when merging a numeric key with an ``object`` key that is not all strings, e.g. ``[1.5, None]``, ``[1.5, "a"]``, or an empty or all-missing key (:issue:`70218`) - Bug in :meth:`DataFrame.pivot` and :func:`pivot` with a list of ``values`` casting the pivoted columns to a common dtype, e.g. integers to ``float64`` or ``object`` (:issue:`43547`)
pandas/core/reshape/tile.py45 + / 7 −
@@ -24,14 +24,18 @@     ensure_platform_int,     is_bool_dtype,     is_integer,+    is_integer_dtype,     is_list_like,     is_numeric_dtype,     is_scalar, ) from pandas.core.dtypes.dtypes import (+    ArrowDtype,+    BaseMaskedDtype,     CategoricalDtype,     DatetimeTZDtype,     ExtensionDtype,+    IntervalDtype, ) from pandas.core.dtypes.generic import ABCSeries from pandas.core.dtypes.missing import isna@@ -271,6 +275,7 @@ def cut(      original = x     x_idx = _preprocess_for_cut(x)+    x_exact = x_idx     x_idx, _ = _coerce_to_type(x_idx)      if not np.iterable(bins):@@ -294,6 +299,7 @@ def cut(         include_lowest=include_lowest,         duplicates=duplicates,         ordered=ordered,+        x_exact=x_exact,     )      return _postprocess_for_cut(fac, bins, retbins, original)@@ -479,6 +485,7 @@ def _bins_to_cuts(     include_lowest: bool = False,     duplicates: str = "raise",     ordered: bool = True,+    x_exact: Index | None = None, ):     if not ordered and labels is None:         raise ValueError("'labels' must be provided if 'ordered = False'")@@ -490,9 +497,12 @@ def _bins_to_cuts(      result: Categorical | np.ndarray +    search_values = x_idx if x_exact is None else _search_values(x_idx, x_exact, bins)+     if isinstance(bins, IntervalIndex):         # we have a fast-path here-        ids = bins.get_indexer(x_idx)+        ids = bins.get_indexer(search_values)+        ids[isna(x_idx)] = -1  # NA may have been filled in search_values         cat_dtype = CategoricalDtype(bins, ordered=True)         result = Categorical.from_codes(ids, dtype=cat_dtype, validate=False)         return result, bins@@ -509,7 +519,7 @@ def _bins_to_cuts(     side: Literal["left", "right"] = "left" if right else "right"      try:-        ids = bins.searchsorted(x_idx, side=side)+        ids = bins.searchsorted(search_values, side=side)     except TypeError as err:         # e.g. test_datetime_nan_error if bins are DatetimeArray and x_idx         #  is integers@@ -527,7 +537,7 @@ def _bins_to_cuts(     ids = ensure_platform_int(ids)      if include_lowest:-        ids[x_idx == bins[0]] = 1+        ids[search_values == bins[0]] = 1      na_mask = isna(x_idx) | (ids == len(bins)) | (ids == 0)     has_nas = na_mask.any()@@ -572,6 +582,36 @@ def _bins_to_cuts(     return result, bins  +def _search_values(x_idx: Index, x_exact: Index, bins: Index) -> Index | np.ndarray:+    """+    Values to compare with ``bins``.++    ``x_idx`` holds nullable and pyarrow integers cast to float64, which loses+    precision above 2**53 (GH#31389). If the original integers fit the dtype of+    integer ``bins``, return them in that dtype instead, with NA filled with 0.+    """+    dtype = x_exact.dtype+    if not isinstance(dtype, (BaseMaskedDtype, ArrowDtype)) or not is_integer_dtype(+        dtype+    ):+        return x_idx++    bins_dtype = bins.dtype+    if isinstance(bins_dtype, IntervalDtype):+        bins_dtype = bins_dtype.subtype+    if isinstance(bins_dtype, (BaseMaskedDtype, ArrowDtype)):+        bins_dtype = bins_dtype.numpy_dtype+    if not lib.is_np_dtype(bins_dtype, "iu"):+        return x_idx++    values = x_exact.to_numpy(dtype=dtype.numpy_dtype, na_value=0)+    info = np.iinfo(bins_dtype)+    if len(values) and (values.min() < info.min or values.max() > info.max):+        # casting would overflow, keep the float64 values+        return x_idx+    return values.astype(bins_dtype, copy=False)++ def _coerce_to_type(x: Index) -> tuple[Index, DtypeObj | None]:     """     if the passed data is of datetime/timedelta, bool or nullable int type,@@ -585,10 +625,8 @@ def _coerce_to_type(x: Index) -> tuple[Index, DtypeObj | None]:     elif is_bool_dtype(x.dtype):         # GH 20303         x = x.astype(np.int64)-    # To support cut and qcut for IntegerArray we convert to float dtype.-    # Will properly support in the future.-    # https://github.com/pandas-dev/pandas/pull/31290-    # https://github.com/pandas-dev/pandas/issues/31389+    # cast to float64 to compute bins; _search_values recovers exact integers+    #  where it can, see GH#31389     elif isinstance(x.dtype, ExtensionDtype) and is_numeric_dtype(x.dtype):         x_arr = x.to_numpy(dtype=np.float64, na_value=np.nan)         x = Index(x_arr, copy=False)
pandas/tests/reshape/test_cut.py52 + / 0 −
@@ -813,6 +813,58 @@ def test_cut_with_nullable_int64():     tm.assert_series_equal(result, expected)  +@pytest.mark.parametrize(+    "dtype", ["Int64", "UInt64", "int64[pyarrow]", "uint64[pyarrow]"]+)+@pytest.mark.parametrize("bins_kind", ["list", "numpy_intervals", "ea_intervals"])+def test_cut_nullable_integer_large_values(dtype, bins_kind):+    # GH#31389 values above 2**53 are not exact in float64+    if "pyarrow" in dtype:+        pytest.importorskip("pyarrow")+    val = 2**60+    ser = pd.Series([val + 1, val + 5, None], dtype=dtype)+    bins = [0, val + 5, val + 6]+    if bins_kind == "numpy_intervals":+        breaks = np.array(bins, dtype=ser.dtype.numpy_dtype)+        bins = pd.IntervalIndex.from_breaks(breaks, closed="left")+    elif bins_kind == "ea_intervals":+        bins = pd.IntervalIndex.from_breaks(pd.array(bins, dtype=dtype), closed="left")+    result = pd.cut(ser, bins, right=False).cat.codes+    expected = pd.Series([0, 1, -1], dtype=np.int8)+    tm.assert_series_equal(result, expected)+++def test_cut_nullable_integer_large_values_include_lowest():+    # GH#31389+    val = 2**60+    ser = pd.Series([val - 1, val + 1, None], dtype="Int64")+    result = pd.cut(ser, [val, val + 2], include_lowest=True, labels=False)+    expected = pd.Series([np.nan, 0, np.nan])+    tm.assert_series_equal(result, expected)+++@pytest.mark.parametrize("dtype", ["UInt64", "uint64[pyarrow]"])+def test_cut_nullable_integer_mixed_signedness(dtype):+    # GH#31389 values that don't fit the bins' dtype must not wrap around+    if "pyarrow" in dtype:+        pytest.importorskip("pyarrow")+    ser = pd.Series([5, 2**64 - 1], dtype=dtype)+    result = pd.cut(ser, [-2, 0, 10], labels=False)+    expected = pd.Series([1, np.nan])+    tm.assert_series_equal(result, expected)+++def test_cut_nullable_integer_masked_interval_bins():+    # GH#31389+    val = 2**60+    ser = pd.Series([val + 1, val + 5, None], dtype="Int64")+    breaks = pd.array([0, val + 5, val + 6], dtype="UInt64")+    bins = pd.IntervalIndex.from_breaks(breaks, closed="left")+    result = pd.cut(ser, bins).cat.codes+    expected = pd.Series([0, 1, -1], dtype=np.int8)+    tm.assert_series_equal(result, expected)++ @pytest.mark.parametrize("closed", ["left", "right", "both", "neither"]) def test_cut_intervalindex_closed(closed):     # GH#47614 - pd.cut with IntervalIndex bins and all closed values