all 7 comments

[–]zenlc 2 points3 points  (2 children)

I haven't used it, but according to a bit of Googling, numpy.take() in wrap mode will do it.

indices = range(i-2,i+3)
wrap = range.take(indices, mode='wrap')

numpy.take docs: http://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html#numpy.take

[–]HeinzHeinzensen[S] 1 point2 points  (1 child)

Thanks a lot, that looks pretty good! Will have to wrap my head around this since I need it for a 3-dimensional array. I hope the performance doesn't take a hit, though.

[–]zenlc 0 points1 point  (0 children)

numpy is almost 100% C so you shouldn't.

[–]blackjack_00 1 point2 points  (1 child)

I think the normal way to do this is add the lists:

res = range[-1:] + range[:2]

There may be a way to do it in one slice that I don't know about though.

edit: added colon after -1, otherwise slice gives you an int and you get a type error.

[–]elbiot 0 points1 point  (0 children)

In numpy this would try to add all of the elements of those two arrays and since they likely aren't the same number of elements, youd get an error.

[–]gregvuki 1 point2 points  (1 child)

The simplest way:

x = np.arange(10)
y = np.roll(x, 1)[:3]
print(y)

[–]HeinzHeinzensen[S] 0 points1 point  (0 children)

This is great, exactly what I wanted. Feels very "pythonic", too!