I want to replace outliners from a list. Therefore I define a upper and lower bound. Now every value above upper_bound
and under lower_bound
is replaced with the bound value. My approach was to do this in two steps using a numpy array.
Now I wonder if it's possible to do this in one step, as I guess it could improve performance and readability.
Is there a shorter way to do this?
import numpy as np
lowerBound, upperBound = 3, 7
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
arr[arr > upperBound] = upperBound
arr[arr < lowerBound] = lowerBound
# [3 3 3 3 4 5 6 7 7 7]
print(arr)
See How can I clamp (clip, restrict) a number to some range? for clamping individual values, including non-Numpy approaches.
clip
method, there's nothing un-pythonic about your code. It is a perfectly good use ofnumpy
, and just as readable (to an experienced user). Keep that concept in your toolbox; it works in cases that don't quite fit theclip
model. – Dippoldclip
method but there is another reason than speed; your code is elegant but creates an intermediate array witharr > upperBound
which could be an issue if the array gets large. – Unrequitedclip()
method is enough for my special use case. The steps 1) doing it on your own 2) understanding the concept and 3) using a library are a good way to go :) – Deposition