Skip to content
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
3 changes: 3 additions & 0 deletions doc/source/whatsnew/v0.23.5.txt
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ Fixed Regressions
- Constructing a DataFrame with an index argument that wasn't already an
instance of :class:`~pandas.core.Index` was broken in `4efb39f
<https://github.com/pandas-dev/pandas/commit/4efb39f01f5880122fa38d91e12d217ef70fad9e>`_ (:issue:`22227`).
- Calling :meth:`DataFrameGroupBy.rank` and :meth:`SeriesGroupBy.rank` with empty groups
and ``pct=True`` was raising a ``ZeroDivisionError`` due to `c1068d9
<https://github.com/pandas-dev/pandas/commit/c1068d9d242c22cb2199156f6fb82eb5759178ae>`_ (:issue:`22519`)
-
-

Expand Down
7 changes: 6 additions & 1 deletion pandas/_libs/groupby_helper.pxi.in
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,12 @@ def group_rank_{{name}}(ndarray[float64_t, ndim=2] out,

if pct:
for i in range(N):
out[i, 0] = out[i, 0] / grp_sizes[i, 0]
# We don't include NaN values in percentage
# rankings, so we assign them percentages of NaN.
if out[i, 0] != out[i, 0] or out[i, 0] == NAN:
out[i, 0] = NAN
else:
out[i, 0] = out[i, 0] / grp_sizes[i, 0]
{{endif}}
{{endfor}}

Expand Down
19 changes: 18 additions & 1 deletion pandas/tests/groupby/test_rank.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pytest
import numpy as np
import pandas as pd
from pandas import DataFrame, concat
from pandas import DataFrame, Series, concat
from pandas.util import testing as tm


Expand Down Expand Up @@ -273,3 +273,20 @@ def test_rank_naoption_raises(ties_method, ascending, na_option, pct, vals):
df.groupby('key').rank(method=ties_method,
ascending=ascending,
na_option=na_option, pct=pct)


def test_rank_empty_group():
# see gh-22519
column = "A"
df = DataFrame({
"A": [0, 1, 0],
"B": [1., np.nan, 2.]
})

result = df.groupby(column).B.rank(pct=True)
expected = Series([0.5, np.nan, 1.0], name="B")
tm.assert_series_equal(result, expected)

result = df.groupby(column).rank(pct=True)
expected = DataFrame({"B": [0.5, np.nan, 1.0]})
tm.assert_frame_equal(result, expected)