将系列或数组约束为一定范围的值 [英] constrain a series or array to a range of values

查看:74
本文介绍了将系列或数组约束为一定范围的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将一系列值限制在+1和-1之内.

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))

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

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

推荐答案

使用示例输入:

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

这篇关于将系列或数组约束为一定范围的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆