1

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?

2
  • 1
    What are the inputs (input arrays and input parameters) and what's the expected output for the sample? In essence, could you convert your sample code to a function format? Commented Nov 12, 2016 at 17:16
  • What do you mean by padding? Commented Nov 12, 2016 at 19:30

2 Answers 2

2

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)
    else:
        s = slice(None, i)
    return np.roll(a, i)[s]
Sign up to request clarification or add additional context in comments.

3 Comments

possible one liner: np.roll(a,i)[slice(i,None) if i>0 else (slice(None,i) if i<0 else slice(None))]
@hpaulj: A better one-liner - a[-i:] if i <= 0 else a[:-i]
np.s_[i:] is also IMO a better way to spell slice(i, None)
1

Why are you even using roll here? The whole point of roll is to create wrap-around behaviour, which is exactly the feature that you seem to be trying to eliminate. A simple slice is sufficient:

def shift_right(arr, i):
    if i <= 0:
        return arr[-i:]
    else:
        return arr[:-i]

This function behaves exactly as the one in David's answer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.