Skip to content

Commit 70cee7c

Browse files
yuanx749pmhatre1
authored andcommitted
BUG: fix groupby.quantile inconsistency when interpolation='nearest' (pandas-dev#56926)
* BUG: fix groupby.quantile inconsistency when interpolation='nearest' * add whatsnew * Add comment
1 parent a53e69c commit 70cee7c

File tree

3 files changed

+5
-15
lines changed

3 files changed

+5
-15
lines changed

doc/source/whatsnew/v2.3.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ Plotting
187187

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

193193
Reshaping

pandas/_libs/groupby.pyx

+3-1
Original file line numberDiff line numberDiff line change
@@ -1286,7 +1286,9 @@ def group_quantile(
12861286
elif interp == INTERPOLATION_MIDPOINT:
12871287
out[i, k] = (val + next_val) / 2.0
12881288
elif interp == INTERPOLATION_NEAREST:
1289-
if frac > .5 or (frac == .5 and q_val > .5): # Always OK?
1289+
if frac > .5 or (frac == .5 and idx % 2 == 1):
1290+
# If quantile lies in the middle of two indexes,
1291+
# take the even index, as np.quantile.
12901292
out[i, k] = next_val
12911293
else:
12921294
out[i, k] = val

pandas/tests/groupby/methods/test_quantile.py

+1-13
Original file line numberDiff line numberDiff line change
@@ -38,19 +38,7 @@
3838
],
3939
)
4040
@pytest.mark.parametrize("q", [0, 0.25, 0.5, 0.75, 1])
41-
def test_quantile(interpolation, a_vals, b_vals, q, request):
42-
if (
43-
interpolation == "nearest"
44-
and q == 0.5
45-
and isinstance(b_vals, list)
46-
and b_vals == [4, 3, 2, 1]
47-
):
48-
request.applymarker(
49-
pytest.mark.xfail(
50-
reason="Unclear numpy expectation for nearest "
51-
"result with equidistant data"
52-
)
53-
)
41+
def test_quantile(interpolation, a_vals, b_vals, q):
5442
all_vals = pd.concat([pd.Series(a_vals), pd.Series(b_vals)])
5543

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

0 commit comments

Comments
 (0)