Skip to content

BUG: Handle floating point boundaries in qcut #59409

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 9, 2024
Merged
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,7 @@ Groupby/resample/rolling

Reshaping
^^^^^^^^^
- Bug in :func:`qcut` where values at the quantile boundaries could be incorrectly assigned (:issue:`59355`)
- Bug in :meth:`DataFrame.join` inconsistently setting result index name (:issue:`55815`)
- Bug in :meth:`DataFrame.unstack` producing incorrect results when ``sort=False`` (:issue:`54987`, :issue:`55516`)
- Bug in :meth:`DataFrame.unstack` producing incorrect results when manipulating empty :class:`DataFrame` with an :class:`ExtentionDtype` (:issue:`59123`)
Expand Down
20 changes: 10 additions & 10 deletions pandas/core/array_algos/quantile.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ def quantile_with_mask(
flat = np.array([fill_value] * len(qs))
result = np.repeat(flat, len(values)).reshape(len(values), len(qs))
else:
result = _nanpercentile(
result = _nanquantile(
values,
qs * 100.0,
qs,
na_value=fill_value,
mask=mask,
interpolation=interpolation,
Expand All @@ -108,15 +108,15 @@ def quantile_with_mask(
return result


def _nanpercentile_1d(
def _nanquantile_1d(
values: np.ndarray,
mask: npt.NDArray[np.bool_],
qs: npt.NDArray[np.float64],
na_value: Scalar,
interpolation: str,
) -> Scalar | np.ndarray:
"""
Wrapper for np.percentile that skips missing values, specialized to
Wrapper for np.quantile that skips missing values, specialized to
1-dimensional case.

Parameters
Expand All @@ -142,7 +142,7 @@ def _nanpercentile_1d(
# equiv: 'np.array([na_value] * len(qs))' but much faster
return np.full(len(qs), na_value)

return np.percentile(
return np.quantile(
values,
qs,
# error: No overload variant of "percentile" matches argument
Expand All @@ -152,7 +152,7 @@ def _nanpercentile_1d(
)


def _nanpercentile(
def _nanquantile(
values: np.ndarray,
qs: npt.NDArray[np.float64],
*,
Expand All @@ -161,7 +161,7 @@ def _nanpercentile(
interpolation: str,
):
"""
Wrapper for np.percentile that skips missing values.
Wrapper for np.quantile that skips missing values.

Parameters
----------
Expand All @@ -180,7 +180,7 @@ def _nanpercentile(

if values.dtype.kind in "mM":
# need to cast to integer to avoid rounding errors in numpy
result = _nanpercentile(
result = _nanquantile(
values.view("i8"),
qs=qs,
na_value=na_value.view("i8"),
Expand All @@ -196,7 +196,7 @@ def _nanpercentile(
# Caller is responsible for ensuring mask shape match
assert mask.shape == values.shape
result = [
_nanpercentile_1d(val, m, qs, na_value, interpolation=interpolation)
_nanquantile_1d(val, m, qs, na_value, interpolation=interpolation)
for (val, m) in zip(list(values), list(mask))
]
if values.dtype.kind == "f":
Expand All @@ -215,7 +215,7 @@ def _nanpercentile(
result = result.astype(values.dtype, copy=False)
return result
else:
return np.percentile(
return np.quantile(
values,
qs,
axis=1,
Expand Down
11 changes: 10 additions & 1 deletion pandas/core/reshape/tile.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,16 @@ def qcut(
x_idx = _preprocess_for_cut(x)
x_idx, _ = _coerce_to_type(x_idx)

quantiles = np.linspace(0, 1, q + 1) if is_integer(q) else q
if is_integer(q):
quantiles = np.linspace(0, 1, q + 1)
# Round up rather than to nearest if not representable in base 2
np.putmask(
quantiles,
q * quantiles != np.arange(q + 1),
np.nextafter(quantiles, 1),
)
else:
quantiles = q

bins = x_idx.to_series().dropna().quantile(quantiles)

Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/reshape/test_qcut.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,3 +307,15 @@ def test_qcut_nullable_integer(q, any_numeric_ea_dtype):
expected = qcut(arr.astype(float), q)

tm.assert_categorical_equal(result, expected)


@pytest.mark.parametrize("scale", [1.0, 1 / 3, 17.0])
@pytest.mark.parametrize("q", [3, 7, 9])
@pytest.mark.parametrize("precision", [1, 3, 16])
def test_qcut_contains(scale, q, precision):
# GH-59355
arr = (scale * np.arange(q + 1)).round(precision)
result = qcut(arr, q, precision=precision)

for value, bucket in zip(arr, result):
assert value in bucket