Skip to content

Commit 9de04bf

Browse files
committed
BUG: Maintain column order with groupby.nth
1 parent b9e2278 commit 9de04bf

File tree

4 files changed

+40
-8
lines changed

4 files changed

+40
-8
lines changed

doc/source/whatsnew/v0.24.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -1212,6 +1212,7 @@ Groupby/Resample/Rolling
12121212
- Bug in :meth:`SeriesGroupBy.mean` when values were integral but could not fit inside of int64, overflowing instead. (:issue:`22487`)
12131213
- :func:`RollingGroupby.agg` and :func:`ExpandingGroupby.agg` now support multiple aggregation functions as parameters (:issue:`15072`)
12141214
- Bug in :meth:`DataFrame.resample` and :meth:`Series.resample` when resampling by a weekly offset (``'W'``) across a DST transition (:issue:`9119`, :issue:`21459`)
1215+
- Bug in :func:`pandas.core.groupby.GroupBy.nth` where column order was not always preserved (:issue:`20760`)
12151216

12161217
Reshaping
12171218
^^^^^^^^^

pandas/core/groupby/groupby.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -491,7 +491,8 @@ def _set_group_selection(self):
491491

492492
if len(groupers):
493493
# GH12839 clear selected obj cache when group selection changes
494-
self._group_selection = ax.difference(Index(groupers)).tolist()
494+
self._group_selection = ax.difference(Index(groupers),
495+
sort=False).tolist()
495496
self._reset_cache('_selected_obj')
496497

497498
def _set_result_index_ordered(self, result):

pandas/core/indexes/base.py

+13-7
Original file line numberDiff line numberDiff line change
@@ -2919,17 +2919,20 @@ def intersection(self, other):
29192919
taken.name = None
29202920
return taken
29212921

2922-
def difference(self, other):
2922+
def difference(self, other, sort=True):
29232923
"""
29242924
Return a new Index with elements from the index that are not in
29252925
`other`.
29262926
29272927
This is the set difference of two Index objects.
2928-
It's sorted if sorting is possible.
29292928
29302929
Parameters
29312930
----------
29322931
other : Index or array-like
2932+
sort : bool, default True
2933+
Sort the resulting index if possible
2934+
2935+
.. versionadded:: 0.24.0
29332936
29342937
Returns
29352938
-------
@@ -2938,10 +2941,12 @@ def difference(self, other):
29382941
Examples
29392942
--------
29402943
2941-
>>> idx1 = pd.Index([1, 2, 3, 4])
2944+
>>> idx1 = pd.Index([2, 1, 3, 4])
29422945
>>> idx2 = pd.Index([3, 4, 5, 6])
29432946
>>> idx1.difference(idx2)
29442947
Int64Index([1, 2], dtype='int64')
2948+
>>> idx1.difference(idx2, sort=False)
2949+
Int64Index([2, 1], dtype='int64')
29452950
29462951
"""
29472952
self._assert_can_do_setop(other)
@@ -2959,10 +2964,11 @@ def difference(self, other):
29592964
label_diff = np.setdiff1d(np.arange(this.size), indexer,
29602965
assume_unique=True)
29612966
the_diff = this.values.take(label_diff)
2962-
try:
2963-
the_diff = sorting.safe_sort(the_diff)
2964-
except TypeError:
2965-
pass
2967+
if sort:
2968+
try:
2969+
the_diff = sorting.safe_sort(the_diff)
2970+
except TypeError:
2971+
pass
29662972

29672973
return this._shallow_copy(the_diff, name=result_name, freq=None)
29682974

pandas/tests/groupby/test_nth.py

+24
Original file line numberDiff line numberDiff line change
@@ -390,3 +390,27 @@ def test_nth_empty():
390390
names=['a', 'b']),
391391
columns=['c'])
392392
assert_frame_equal(result, expected)
393+
394+
395+
def test_nth_column_order():
396+
# GH 20760
397+
# Check that nth preserves column order
398+
df = DataFrame([[1, 'b', 100],
399+
[1, 'a', 50],
400+
[1, 'a', np.nan],
401+
[2, 'c', 200],
402+
[2, 'd', 150]],
403+
columns=['A', 'C', 'B'])
404+
result = df.groupby('A').nth(0)
405+
expected = DataFrame([['b', 100.0],
406+
['c', 200.0]],
407+
columns=['C', 'B'],
408+
index=Index([1, 2], name='A'))
409+
assert_frame_equal(result, expected)
410+
411+
result = df.groupby('A').nth(-1, dropna='any')
412+
expected = DataFrame([['a', 50.0],
413+
['d', 150.0]],
414+
columns=['C', 'B'],
415+
index=Index([1, 2], name='A'))
416+
assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)