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?

匆匆过客 提交于 2020-01-03 01:35:09

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/57696153/is-there-a-function-like-numpy-clipa-a-min-a-max-where-values-outside-a-min

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!