Skip to content

BUG: fix groupby.quantile inconsistency when interpolation='nearest' #56926

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 4 commits into from
Jan 18, 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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ Plotting

Groupby/resample/rolling
^^^^^^^^^^^^^^^^^^^^^^^^
-
- Bug in :meth:`.DataFrameGroupBy.quantile` when ``interpolation="nearest"`` is inconsistent with :meth:`DataFrame.quantile` (:issue:`47942`)
-

Reshaping
Expand Down
4 changes: 3 additions & 1 deletion pandas/_libs/groupby.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1286,7 +1286,9 @@ def group_quantile(
elif interp == INTERPOLATION_MIDPOINT:
out[i, k] = (val + next_val) / 2.0
elif interp == INTERPOLATION_NEAREST:
if frac > .5 or (frac == .5 and q_val > .5): # Always OK?
if frac > .5 or (frac == .5 and idx % 2 == 1):
# If quantile lies in the middle of two indexes,
# take the even index, as np.quantile.
out[i, k] = next_val
else:
out[i, k] = val
Expand Down
14 changes: 1 addition & 13 deletions pandas/tests/groupby/methods/test_quantile.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,19 +38,7 @@
],
)
@pytest.mark.parametrize("q", [0, 0.25, 0.5, 0.75, 1])
def test_quantile(interpolation, a_vals, b_vals, q, request):
if (
interpolation == "nearest"
and q == 0.5
and isinstance(b_vals, list)
and b_vals == [4, 3, 2, 1]
):
request.applymarker(
pytest.mark.xfail(
reason="Unclear numpy expectation for nearest "
"result with equidistant data"
)
)
def test_quantile(interpolation, a_vals, b_vals, q):
all_vals = pd.concat([pd.Series(a_vals), pd.Series(b_vals)])

a_expected = pd.Series(a_vals).quantile(q, interpolation=interpolation)
Expand Down