问题
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