6
votes

Say I have a numpy array:

>>> a 
array([0,1,2,3,4])

and I want to "rotate" it to get:

>>> b
array([4,0,1,2,3])

What is the best way?

I have been converting to a deque and back (see below) but is there a better way?

b = deque(a)
b.rotate(1)
b = np.array(b)
3
Just to be pedantic, a.shape is (n,) not (n,1) - askewchan
@askewchan, I think that (n,) and (n,1) arrays look the same. Am I wrong? - atomh33ls
You're right that they look the same, and even behave the same in many circumstances, including the roll function, but be careful in some cases where ndim might matter (for a.shape is (n,), a.ndim is 1; but for shape (n,1), a.ndim is 2). As you can see from the question you linked to, an axis must be added to get from the 1d to 2d case. - askewchan
Fair point. In hindsight, to be consistent with the question title, I should have shown a with an (n,1) shape as array([[0],[1],[2],[3],[4]]). However, each of the answers does work for both (n,) and (n,1) shapes. - atomh33ls
Yes, roll will be effectively be applied along the non-1 axis if there is only one, which is why my comment was nothing beyond pedantry :). But if your array is (n,m) (or higher) it will roll along all the axes (the flattened array) which might give unexpected results. The solution there is to just do np.roll(a, axis=0) - askewchan

3 Answers

12
votes

Just use the numpy.roll function:

a = np.array([0,1,2,3,4])
b = np.roll(a,1)
print(b)
>>> [4 0 1 2 3]

See also this question.

2
votes
numpy.concatenate([a[-1:], a[:-1]])
>>> array([4, 0, 1, 2, 3])
1
votes

Try this one

b = a[-1:]+a[:-1]