Skip to content

Commit f957330

Browse files
REGR: DataFrame.apply() with raw option and func returning string (#36610)
1 parent 209c29e commit f957330

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

doc/source/whatsnew/v1.1.3.rst

+1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ Fixed regressions
3535
- Fixed regression in :meth:`Series.__getitem__` incorrectly raising when the input was a frozenset (:issue:`35747`)
3636
- Fixed regression in :meth:`read_excel` with ``engine="odf"`` caused ``UnboundLocalError`` in some cases where cells had nested child nodes (:issue:`36122`, :issue:`35802`)
3737
- Fixed regression in :class:`DataFrame` and :class:`Series` comparisons between numeric arrays and strings (:issue:`35700`, :issue:`36377`)
38+
- Fixed regression in :meth:`DataFrame.apply` with ``raw=True`` and user-function returning string (:issue:`35940`)
3839
- Fixed regression when setting empty :class:`DataFrame` column to a :class:`Series` in preserving name of index in frame (:issue:`36527`)
3940
- Fixed regression in :class:`Period` incorrect value for ordinal over the maximum timestamp (:issue:`36430`)
4041

pandas/core/apply.py

+17-1
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,23 @@ def apply_empty_result(self):
216216

217217
def apply_raw(self):
218218
""" apply to the values as a numpy array """
219-
result = np.apply_along_axis(self.f, self.axis, self.values)
219+
220+
def wrap_function(func):
221+
"""
222+
Wrap user supplied function to work around numpy issue.
223+
224+
see https://github.com/numpy/numpy/issues/8352
225+
"""
226+
227+
def wrapper(*args, **kwargs):
228+
result = func(*args, **kwargs)
229+
if isinstance(result, str):
230+
result = np.array(result, dtype=object)
231+
return result
232+
233+
return wrapper
234+
235+
result = np.apply_along_axis(wrap_function(self.f), self.axis, self.values)
220236

221237
# TODO: mixed type case
222238
if result.ndim == 2:

pandas/tests/frame/apply/test_frame_apply.py

+8
Original file line numberDiff line numberDiff line change
@@ -1545,3 +1545,11 @@ def test_apply_no_suffix_index():
15451545
)
15461546

15471547
tm.assert_frame_equal(result, expected)
1548+
1549+
1550+
def test_apply_raw_returns_string():
1551+
# https://github.com/pandas-dev/pandas/issues/35940
1552+
df = pd.DataFrame({"A": ["aa", "bbb"]})
1553+
result = df.apply(lambda x: x[0], axis=1, raw=True)
1554+
expected = pd.Series(["aa", "bbb"])
1555+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)