LWZ
LWZ

Reputation: 12348

how to do circular shift in numpy

I have a numpy array, for example

a = np.arange(10)

how can I move the first n elements to the end of the array?

I found this roll function but it seems like it only does the opposite, which shifts the last n elements to the beginning.

Upvotes: 22

Views: 56770

Answers (2)

Francesco Montesano
Francesco Montesano

Reputation: 8668

you can use negative shift

a = np.arange(10)
print(np.roll(a, 3))
print(np.roll(a, -3))

returns

[7, 8, 9, 0, 1, 2, 3, 4, 5, 6]
[3, 4, 5, 6, 7, 8, 9, 0, 1, 2]

Upvotes: 8

mgilson
mgilson

Reputation: 310049

Why not just roll with a negative number?

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

Upvotes: 60

Related Questions