Brian Brian - 4 months ago 8
Python Question

constrain a series or array to a range of values

I have a series of values that I want to have constrained to be within +1 and -1.

s = pd.Series(np.random.randn(10000))


I know I can use
apply
, but is there a simple vectorized approach?

s_ = s.apply(lambda x: min(max(x, -1), 1))
s_.head()

0 -0.256117
1 0.879797
2 1.000000
3 -0.711397
4 -0.400339
dtype: float64

Answer

Use clip:

s = s.clip(-1,1)

Example Input:

s = pd.Series([-1.2, -0.5, 1, 1.1])

0   -1.2
1   -0.5
2    1.0
3    1.1

Example Output:

0   -1.0
1   -0.5
2    1.0
3    1.0