Skip to content

Commit 39715d6

Browse files
committed
BUG: Maintain column order with groupby.nth
1 parent c8ce3d0 commit 39715d6

File tree

4 files changed

+40
-8
lines changed

4 files changed

+40
-8
lines changed

Diff for: doc/source/whatsnew/v0.24.0.txt

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

891892
Sparse
892893
^^^^^^

Diff for: pandas/core/groupby/groupby.py

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

498498
if len(groupers):
499499
# GH12839 clear selected obj cache when group selection changes
500-
self._group_selection = ax.difference(Index(groupers)).tolist()
500+
self._group_selection = ax.difference(Index(groupers),
501+
sort=False).tolist()
501502
self._reset_cache('_selected_obj')
502503

503504
def _set_result_index_ordered(self, result):

Diff for: pandas/core/indexes/base.py

+13-7
Original file line numberDiff line numberDiff line change
@@ -2901,17 +2901,20 @@ def intersection(self, other):
29012901
taken.name = None
29022902
return taken
29032903

2904-
def difference(self, other):
2904+
def difference(self, other, sort=True):
29052905
"""
29062906
Return a new Index with elements from the index that are not in
29072907
`other`.
29082908
29092909
This is the set difference of two Index objects.
2910-
It's sorted if sorting is possible.
29112910
29122911
Parameters
29132912
----------
29142913
other : Index or array-like
2914+
sort : bool, default True
2915+
Sort the resulting index if possible
2916+
2917+
.. versionadded:: 0.24.0
29152918
29162919
Returns
29172920
-------
@@ -2920,10 +2923,12 @@ def difference(self, other):
29202923
Examples
29212924
--------
29222925
2923-
>>> idx1 = pd.Index([1, 2, 3, 4])
2926+
>>> idx1 = pd.Index([2, 1, 3, 4])
29242927
>>> idx2 = pd.Index([3, 4, 5, 6])
29252928
>>> idx1.difference(idx2)
29262929
Int64Index([1, 2], dtype='int64')
2930+
>>> idx1.difference(idx2, sort=False)
2931+
Int64Index([2, 1], dtype='int64')
29272932
29282933
"""
29292934
self._assert_can_do_setop(other)
@@ -2941,10 +2946,11 @@ def difference(self, other):
29412946
label_diff = np.setdiff1d(np.arange(this.size), indexer,
29422947
assume_unique=True)
29432948
the_diff = this.values.take(label_diff)
2944-
try:
2945-
the_diff = sorting.safe_sort(the_diff)
2946-
except TypeError:
2947-
pass
2949+
if sort:
2950+
try:
2951+
the_diff = sorting.safe_sort(the_diff)
2952+
except TypeError:
2953+
pass
29482954

29492955
return this._shallow_copy(the_diff, name=result_name, freq=None)
29502956

Diff for: 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)