Skip to content

Commit 626448d

Browse files
authored
BUG: DataFrame.apply axis=1 for str ops with no axis argument (#39212)
1 parent 77e488b commit 626448d

File tree

3 files changed

+13
-0
lines changed

3 files changed

+13
-0
lines changed

doc/source/whatsnew/v1.3.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,7 @@ Reshaping
348348
- Bug in :func:`join` over :class:`MultiIndex` returned wrong result, when one of both indexes had only one level (:issue:`36909`)
349349
- :meth:`merge_asof` raises ``ValueError`` instead of cryptic ``TypeError`` in case of non-numerical merge columns (:issue:`29130`)
350350
- 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`)
351+
- 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`)
351352
-
352353

353354
Sparse

pandas/core/apply.py

+2
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,8 @@ def maybe_apply_str(self) -> Optional[FrameOrSeriesUnion]:
193193
sig = inspect.getfullargspec(func)
194194
if "axis" in sig.args:
195195
self.kwds["axis"] = self.axis
196+
elif self.axis != 0:
197+
raise ValueError(f"Operation {f} does not support axis=1")
196198
return self.obj._try_aggregate_string_function(f, *self.args, **self.kwds)
197199

198200
def maybe_apply_multiple(self) -> Optional[FrameOrSeriesUnion]:

pandas/tests/frame/apply/test_frame_apply.py

+10
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,16 @@ def test_apply_with_string_funcs(self, request, float_frame, func, args, kwds, h
177177
expected = getattr(float_frame, func)(*args, **kwds)
178178
tm.assert_series_equal(result, expected)
179179

180+
@pytest.mark.parametrize(
181+
"how, args", [("pct_change", ()), ("nsmallest", (1, ["a", "b"])), ("tail", 1)]
182+
)
183+
def test_apply_str_axis_1_raises(self, how, args):
184+
# GH 39211 - some ops don't support axis=1
185+
df = DataFrame({"a": [1, 2], "b": [3, 4]})
186+
msg = f"Operation {how} does not support axis=1"
187+
with pytest.raises(ValueError, match=msg):
188+
df.apply(how, axis=1, args=args)
189+
180190
def test_apply_broadcast(self, float_frame, int_frame_const_col):
181191

182192
# scalars

0 commit comments

Comments
 (0)