Skip to content

PERF: fix some of .clip() performance regression by using numpy arrays where possible #24735

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 20, 2019
Merged
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 asv_bench/benchmarks/series_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,11 +140,13 @@ def time_map(self, mapper):


class Clip(object):
params = [50, 1000, 10**5]
param_names = ['n']

def setup(self):
self.s = Series(np.random.randn(50))
def setup(self, n):
self.s = Series(np.random.randn(n))

def time_clip(self):
def time_clip(self, n):
self.s.clip(0, 1)


Expand Down
18 changes: 12 additions & 6 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -7148,12 +7148,18 @@ def _clip_with_scalar(self, lower, upper, inplace=False):
raise ValueError("Cannot use an NA value as a clip threshold")

result = self
if upper is not None:
subset = self.le(upper, axis=None) | isna(result)
result = result.where(subset, upper, axis=None, inplace=False)
if lower is not None:
subset = self.ge(lower, axis=None) | isna(result)
result = result.where(subset, lower, axis=None, inplace=False)
mask = isna(self.values)

with np.errstate(all='ignore'):
Copy link
Member

Choose a reason for hiding this comment

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

What's the point of this?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is simply reverting back to what this block used to do; it's needed in the event values <= upper would otherwise raise a type error.

if upper is not None:
subset = self.to_numpy() <= upper
result = result.where(subset, upper, axis=None, inplace=False)
if lower is not None:
subset = self.to_numpy() >= lower
result = result.where(subset, lower, axis=None, inplace=False)

if np.any(mask):
result[mask] = np.nan

if inplace:
self._update_inplace(result)
Expand Down