Liam Coatman Liam Coatman - 1 year ago 166
Python Question

Roll numpy array without padding?

I have an array a=np.arange(10). I want to use np.roll, where the shift can be positive or negative. I then want to use indexing to remove the elements which have been padded to the beginning (if the shift is positive) or end (if the shift is negative) of the array. So for example:

a = np.arange(10)
np.roll(a, 1)[1:] = array([0, 1, 2, 3, 4, 5, 6, 7, 8])
np.roll(a, -1)[:-1] = array([1, 2, 3, 4, 5, 6, 7, 8, 9])

Is there a generic way to accomplish this in a single line?

Answer Source

I don't think its possible to do this in a generic (not hard-coded way). But its pretty easy to write a short function that does what you want.

def roll2(arr, i):
    """Roll and clip array"""
    if i == 0:
        return arr
    elif i > 0:
        s = slice(i, None)
        s = slice(None, i)
    return np.roll(a, i)[s]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download