Skip to content

Commit dc7d022

Browse files
committed
BUG: bug in groupby on empty frame with multi groupers
xref pandas-dev#14784
1 parent 50d2c69 commit dc7d022

File tree

3 files changed

+20
-5
lines changed

3 files changed

+20
-5
lines changed

doc/source/whatsnew/v0.20.0.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1600,7 +1600,7 @@ Indexing
16001600
- Bug in the HTML display with with a ``MultiIndex`` and truncation (:issue:`14882`)
16011601
- Bug in the display of ``.info()`` where a qualifier (+) would always be displayed with a ``MultiIndex`` that contains only non-strings (:issue:`15245`)
16021602
- Bug in ``pd.concat()`` where the names of ``MultiIndex`` of resulting ``DataFrame`` are not handled correctly when ``None`` is presented in the names of ``MultiIndex`` of input ``DataFrame`` (:issue:`15787`)
1603-
- Bug in ``DataFrame.sort_index()`` and ``Series.sort_index()`` where ``na_position`` doesn't work with a ``MultiIndex`` (:issue:`14784`)
1603+
- Bug in ``DataFrame.sort_index()`` and ``Series.sort_index()`` where ``na_position`` doesn't work with a ``MultiIndex`` (:issue:`14784`, :issue:`16604`)
16041604

16051605
I/O
16061606
^^^

pandas/core/indexes/multi.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1645,10 +1645,11 @@ def _get_labels_for_sorting(self):
16451645
"""
16461646
from pandas.core.categorical import Categorical
16471647

1648-
return [Categorical.from_codes(label,
1649-
np.arange(np.array(label).max() + 1,
1650-
dtype=label.dtype),
1651-
ordered=True)
1648+
def cats(label):
1649+
return np.arange(np.array(label).max() + 1 if len(label) else 0,
1650+
dtype=label.dtype)
1651+
1652+
return [Categorical.from_codes(label, cats(label), ordered=True)
16521653
for label in self.labels]
16531654

16541655
def sortlevel(self, level=0, ascending=True, sort_remaining=True):

pandas/tests/groupby/test_nth.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,3 +232,17 @@ def test_nth_multi_index_as_expected(self):
232232
['one', 'two', 'one', 'two']],
233233
names=['A', 'B']))
234234
assert_frame_equal(result, expected)
235+
236+
237+
def test_nth_empty():
238+
# GH 16064
239+
df = DataFrame(index=[0], columns=['a', 'b', 'c'])
240+
result = df.groupby('a').nth(10)
241+
expected = DataFrame(index=Index([], name='a'), columns=['b', 'c'])
242+
assert_frame_equal(result, expected)
243+
244+
result = df.groupby(['a', 'b']).nth(10)
245+
expected = DataFrame(index=MultiIndex([[], []], [[], []],
246+
names=['a', 'b']),
247+
columns=['c'])
248+
assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)