Skip to content

Commit 00e684f

Browse files
authored
BUG: Fix sort_values for empty by argument (#40324)
1 parent 27e0330 commit 00e684f

File tree

3 files changed

+11
-1
lines changed

3 files changed

+11
-1
lines changed

doc/source/whatsnew/v1.3.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,7 @@ Timezones
439439
Numeric
440440
^^^^^^^
441441
- Bug in :meth:`DataFrame.quantile`, :meth:`DataFrame.sort_values` causing incorrect subsequent indexing behavior (:issue:`38351`)
442+
- Bug in :meth:`DataFrame.sort_values` raising an :class:`IndexError` for empty ``by`` (:issue:`40258`)
442443
- Bug in :meth:`DataFrame.select_dtypes` with ``include=np.number`` now retains numeric ``ExtensionDtype`` columns (:issue:`35340`)
443444
- Bug in :meth:`DataFrame.mode` and :meth:`Series.mode` not keeping consistent integer :class:`Index` for empty input (:issue:`33321`)
444445
- Bug in :meth:`DataFrame.rank` with ``np.inf`` and mixture of ``np.nan`` and ``np.inf`` (:issue:`32593`)

pandas/core/frame.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -5818,7 +5818,7 @@ def sort_values( # type: ignore[override]
58185818
keys, orders=ascending, na_position=na_position, key=key
58195819
)
58205820
indexer = ensure_platform_int(indexer)
5821-
else:
5821+
elif len(by):
58225822

58235823
by = by[0]
58245824
k = self._get_label_or_level_values(by, axis=axis)
@@ -5833,6 +5833,8 @@ def sort_values( # type: ignore[override]
58335833
indexer = nargsort(
58345834
k, kind=kind, ascending=ascending, na_position=na_position, key=key
58355835
)
5836+
else:
5837+
return self.copy()
58365838

58375839
new_data = self._mgr.take(
58385840
indexer, axis=self._get_block_manager_axis(axis), verify=False

pandas/tests/frame/methods/test_sort_values.py

+7
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,13 @@ def test_sort_values(self):
7979
with pytest.raises(ValueError, match=msg):
8080
frame.sort_values(by=["A", "B"], axis=0, ascending=[True] * 5)
8181

82+
def test_sort_values_by_empty_list(self):
83+
# https://github.com/pandas-dev/pandas/issues/40258
84+
expected = DataFrame({"a": [1, 4, 2, 5, 3, 6]})
85+
result = expected.sort_values(by=[])
86+
tm.assert_frame_equal(result, expected)
87+
assert result is not expected
88+
8289
def test_sort_values_inplace(self):
8390
frame = DataFrame(
8491
np.random.randn(4, 4), index=[1, 2, 3, 4], columns=["A", "B", "C", "D"]

0 commit comments

Comments
 (0)