diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 44318df408751..310b42e373dae 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -642,6 +642,7 @@ Other - Bug in :meth:`DataFrame.shift` with ``axis=1`` on a :class:`DataFrame` with a single :class:`ExtensionDtype` column giving incorrect results (:issue:`53832`) - Bug in :meth:`Index.sort_values` when a ``key`` is passed (:issue:`52764`) - Bug in :meth:`Series.align`, :meth:`DataFrame.align`, :meth:`Series.reindex`, :meth:`DataFrame.reindex`, :meth:`Series.interpolate`, :meth:`DataFrame.interpolate`, incorrectly failing to raise with method="asfreq" (:issue:`53620`) +- Bug in :meth:`Series.argsort` failing to raise when an invalid ``axis`` is passed (:issue:`54257`) - Bug in :meth:`Series.map` when giving a callable to an empty series, the returned series had ``object`` dtype. It now keeps the original dtype (:issue:`52384`) - Bug in :meth:`Series.memory_usage` when ``deep=True`` throw an error with Series of objects and the returned value is incorrect, as it does not take into account GC corrections (:issue:`51858`) - Bug in :meth:`period_range` the default behavior when freq was not passed as an argument was incorrect(:issue:`53687`) diff --git a/pandas/core/series.py b/pandas/core/series.py index 81eea98ab3f65..21cce4c491e14 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3958,6 +3958,10 @@ def argsort( 2 0 dtype: int64 """ + if axis != -1: + # GH#54257 We allow -1 here so that np.argsort(series) works + self._get_axis_number(axis) + values = self._values mask = isna(values) diff --git a/pandas/tests/series/methods/test_argsort.py b/pandas/tests/series/methods/test_argsort.py index 8549ecb99d061..bb2c29f9acdbb 100644 --- a/pandas/tests/series/methods/test_argsort.py +++ b/pandas/tests/series/methods/test_argsort.py @@ -10,12 +10,20 @@ class TestSeriesArgsort: + def test_argsort_axis(self): + # GH#54257 + ser = Series(range(3)) + + msg = "No axis named 2 for object type Series" + with pytest.raises(ValueError, match=msg): + ser.argsort(axis=2) + def test_argsort_numpy(self, datetime_series): ser = datetime_series - func = np.argsort - tm.assert_numpy_array_equal( - func(ser).values, func(np.array(ser)), check_dtype=False - ) + + res = np.argsort(ser).values + expected = np.argsort(np.array(ser)) + tm.assert_numpy_array_equal(res, expected) # with missing values ts = ser.copy() @@ -25,10 +33,10 @@ def test_argsort_numpy(self, datetime_series): with tm.assert_produces_warning( FutureWarning, match=msg, check_stacklevel=False ): - result = func(ts)[1::2] - expected = func(np.array(ts.dropna())) + result = np.argsort(ts)[1::2] + expected = np.argsort(np.array(ts.dropna())) - tm.assert_numpy_array_equal(result.values, expected, check_dtype=False) + tm.assert_numpy_array_equal(result.values, expected) def test_argsort(self, datetime_series): argsorted = datetime_series.argsort()