将一系列或数组约束到一系列值

时间:2016-07-29 23:25:23

标签: python numpy pandas

我有一系列我希望限制在+1和-1范围内的值。

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

我知道我可以使用apply,但是有一种简单的矢量化方法吗?

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

4 个答案:

答案 0 :(得分:4)

使用clip

s = s.clip(-1,1)

示例输入:

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

0   -1.2
1   -0.5
2    1.0
3    1.1

示例输出:

0   -1.0
1   -0.5
2    1.0
3    1.0

答案 1 :(得分:1)

使用嵌套的np.where

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

时序

enter image description here

答案 2 :(得分:1)

您可以使用between系列方法:

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

注意:此会丢弃超出范围的值。

答案 3 :(得分:0)

还有一个建议:

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