Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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
share|improve this question
up vote 2 down vote accepted

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
share|improve this answer
    
This does something slightly different, but is nonetheless good to know! – Andy Hayden 29 mins ago
    
@AndyHayden: Huh? It gives the same output as what I get running the example code in the question and piRSquared's answer. Or am I missing subtle? – root 26 mins ago
    
mine discards values out of the between range, yours caps them at the min/max. As seen from the 0th item in your example. – Andy Hayden 24 mins ago
    
Ha! clip is what the OP wanted! – Andy Hayden 23 mins ago
    
I didn't know this clip method, ty +1 – piRSquared 19 mins ago

You can use the between Series method:

In [11]: s[s.between(-1, 1)]
Out[11]:
0   -0.256117
1    0.879797
3   -0.711397
4   -0.400339
5    0.667196
...

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

share|improve this answer
    
Ooops, this discards the values outside the between range. Going to leave this here anyway (as it could be what someone finding this answer may want). – Andy Hayden 22 mins ago
    
I was also unaware of between +1. – piRSquared 19 mins ago

Use nested np.where

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

Timing

enter image description here

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.