是否有像 numpy.clip(a, a_min, a_max) 这样的函数,其中 a_min 和 a_max 之外的值被包裹而不是饱和? [英] Is there a function like numpy.clip(a, a_min, a_max) where values outside a_min and a_max are wrapped rather than saturated?
问题描述
对于给定的整数 numpy 数组,我可以使用 numpy.clip(a,a_min,a_max) 将该数组中的值饱和到任意最小值和最大值.我想知道是否有一个 numpy 函数或技巧可以做到这一点,而不是使值饱和,而是将它们包装起来.
我知道,如果我使用某个整数 dtype(例如:int8)创建一个 numpy 数组,那么我将对 [-128,128) 之外的值进行这种包装行为.但是,我想拥有可自定义的边界,即,如何将值包装在 [-10,10) 之间的数组中?
例如,假设我有一个名为 wrap() 的函数,那么我将其用作:
import numpya = numpy.array([10,5,-11,5],dtype=numpy.int64)b = wrap(a,min = -10, max = 10)
然后我希望 b 等于:
array([-10,5,9,5], dtype = int64)
提前致谢.
如果我对问题的理解正确,您可以使用
获得所需的输出<预><代码>>>>((a - min) % (max - min)) + min数组([-10, 5, 9, 5])%
运算符包装值(取 mod),它的其余部分只是设置正确的包装范围.
For a given integer numpy array, I can saturate values in this array to an arbitrary min and max using numpy.clip(a,a_min,a_max). I was wondering if there is a numpy function or trick to doing this so that instead of saturating the values, it wraps them.
I know that if I make a numpy array with a certain integer dtype (for example: int8), then I will have this wrapping behaviour for values outside of [-128,128). However, I want to have customisable bounds, i.e., how would I wrap values in an array between [-10,10)?
For example, say I had such a function named wrap(), then I'd use it as:
import numpy
a = numpy.array([10,5,-11,5],dtype=numpy.int64)
b = wrap(a,min = -10, max = 10)
I'd then expect that b would equal:
array([-10,5,9,5], dtype = int64)
Thanks in advance.
If I'm understanding the question correctly, you can get the desired output with
>>> ((a - min) % (max - min)) + min
array([-10, 5, 9, 5])
The %
operator wraps the values (taking the mod), and the wrest of it just sets the correct range for wrapping.
这篇关于是否有像 numpy.clip(a, a_min, a_max) 这样的函数,其中 a_min 和 a_max 之外的值被包裹而不是饱和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!