Skip to content Skip to sidebar Skip to footer

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 ap

Solution 1:

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

Solution 2:

You can use the between Series method:

In[11]: s[s.between(-1, 1)]Out[11]:
0-0.25611710.8797973-0.7113974-0.40033950.667196
...

Note: This discards the values outside of the between range.

Solution 3:

Use nested np.where

pd.Series(np.where(s < -1, -1, np.where(s > 1, 1, s)))

Timing

enter image description here

Solution 4:

One more suggestion:

s[s<-1] = -1
s[s>1] = 1

Post a Comment for "Constrain A Series Or Array To A Range Of Values"