用Python方法用上下限替换列表值(钳位,裁剪,阈值)? [英] Pythonic way to replace list values with upper and lower bound (clamping, clipping, thresholding)?

查看:671
本文介绍了用Python方法用上下限替换列表值(钳位,裁剪,阈值)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从列表中替换轮廓线.因此,我定义了一个上限和下限.现在,upper_bound之上和lower_bound之下的每个值都将替换为绑定值.我的方法是使用numpy数组分两步完成此操作.

I want to replace outliners from a list. Therefore I define a upper and lower bound. Now every value above upper_bound and under lower_bound is replaced with the bound value. My approach was to do this in two steps using a numpy array.

现在,我想知道是否可以一步完成此操作,因为我猜它可以提高性能和可读性.

Now I wonder if it's possible to do this in one step, as I guess it could improve performance and readability.

是否有更短的方法?

import numpy as np

lowerBound, upperBound = 3, 7

arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

arr[arr > upperBound] = upperBound
arr[arr < lowerBound] = lowerBound

# [3 3 3 3 4 5 6 7 7 7]
print(arr)

推荐答案

您可以使用numpy.clip:

In [1]: import numpy as np

In [2]: arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [3]: lowerBound, upperBound = 3, 7

In [4]: np.clip(arr, lowerBound, upperBound, out=arr)
Out[4]: array([3, 3, 3, 3, 4, 5, 6, 7, 7, 7])

In [5]: arr
Out[5]: array([3, 3, 3, 3, 4, 5, 6, 7, 7, 7])

这篇关于用Python方法用上下限替换列表值(钳位,裁剪,阈值)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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