Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -3872,7 +3872,7 @@ def transform(self, func, axis=0, *args, **kwargs):
self._get_axis_number(axis)
return super().transform(func, *args, **kwargs)

def apply(self, func, convert_dtype=True, args=(), **kwds):
def apply(self, func, convert_dtype=True, force_mapping=False, args=(), **kwds):
"""
Invoke function on values of Series.

Expand All @@ -3886,6 +3886,9 @@ def apply(self, func, convert_dtype=True, args=(), **kwds):
convert_dtype : bool, default True
Try to find better dtype for elementwise function results. If
False, leave as dtype=object.
force_mapping : bool, default False
If set to True, forces func to be called on each element separately.
Useful when using numpy functions.
args : tuple
Positional arguments passed to func after the series value.
**kwds
Expand Down Expand Up @@ -3992,9 +3995,8 @@ def f(x):
f = func

with np.errstate(all="ignore"):
if isinstance(f, np.ufunc):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why would we want to do this?
is going to kill perf

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Issue #33492 describes that. I also added test

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as I said I am not inclided to accept this w/o proof that this does not kill perf. We likely don't have asv's for this (or even using a np.ufunc in apply).

Now if you add those and either perf is not degraded, or you actually catch the TypeError then I would be ok.

if not force_mapping and isinstance(f, np.ufunc):
return f(self)

# row-wise access
if is_extension_array_dtype(self.dtype) and hasattr(self._values, "map"):
# GH#23179 some EAs do not have `map`
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/series/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -813,3 +813,11 @@ def test_apply_to_timedelta(self):
b = Series(list_of_strings).apply(pd.to_timedelta) # noqa
# Can't compare until apply on a Series gives the correct dtype
# assert_series_equal(a, b)

def test_apply_to_numpy_func_with_force_mapping(self):
s = pd.Series([np.array([0.1, 0.2], dtype=float)])
expected = pd.Series(
[np.array([0.09983341664682815, 0.19866933079506122], dtype=float)]
)
result = s.apply(np.sin, force_mapping=True)
tm.assert_series_equal(result, expected)