diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index ab00b749d5725..c601c6f496682 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -346,6 +346,7 @@ Reshaping - Bug in :func:`join` over :class:`MultiIndex` returned wrong result, when one of both indexes had only one level (:issue:`36909`) - :meth:`merge_asof` raises ``ValueError`` instead of cryptic ``TypeError`` in case of non-numerical merge columns (:issue:`29130`) - Bug in :meth:`DataFrame.join` not assigning values correctly when having :class:`MultiIndex` where at least one dimension is from dtype ``Categorical`` with non-alphabetically sorted categories (:issue:`38502`) +- Bug in :meth:`DataFrame.apply` would give incorrect results when used with a string argument and ``axis=1`` when the axis argument was not supported and now raises a ``ValueError`` instead (:issue:`39211`) - Sparse diff --git a/pandas/core/apply.py b/pandas/core/apply.py index f7c7220985138..0246971bfa2b4 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -193,6 +193,8 @@ def maybe_apply_str(self) -> Optional[FrameOrSeriesUnion]: sig = inspect.getfullargspec(func) if "axis" in sig.args: self.kwds["axis"] = self.axis + elif self.axis != 0: + raise ValueError(f"Operation {f} does not support axis=1") return self.obj._try_aggregate_string_function(f, *self.args, **self.kwds) def maybe_apply_multiple(self) -> Optional[FrameOrSeriesUnion]: diff --git a/pandas/tests/frame/apply/test_frame_apply.py b/pandas/tests/frame/apply/test_frame_apply.py index 2b72ba3cf2773..ca006f9733bf2 100644 --- a/pandas/tests/frame/apply/test_frame_apply.py +++ b/pandas/tests/frame/apply/test_frame_apply.py @@ -179,6 +179,16 @@ def test_apply_with_string_funcs(self, request, float_frame, func, args, kwds, h expected = getattr(float_frame, func)(*args, **kwds) tm.assert_series_equal(result, expected) + @pytest.mark.parametrize( + "how, args", [("pct_change", ()), ("nsmallest", (1, ["a", "b"])), ("tail", 1)] + ) + def test_apply_str_axis_1_raises(self, how, args): + # GH 39211 - some ops don't support axis=1 + df = DataFrame({"a": [1, 2], "b": [3, 4]}) + msg = f"Operation {how} does not support axis=1" + with pytest.raises(ValueError, match=msg): + df.apply(how, axis=1, args=args) + def test_apply_broadcast(self, float_frame, int_frame_const_col): # scalars