6

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)
Lee
  • 29,398
  • 28
  • 117
  • 170
  • Just to be pedantic, `a.shape` is `(n,)` not `(n,1)` – askewchan Apr 15 '13 at 02:48
  • @askewchan, I think that (n,) and (n,1) arrays [look the same](http://stackoverflow.com/questions/7635237/numpy-syntax-idiom-to-cast-n-array-to-a-n-1-array). Am I wrong? – Lee Apr 15 '13 at 10:21
  • 1
    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 Apr 15 '13 at 12:51
  • 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. – Lee Apr 15 '13 at 14:50
  • 1
    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 Apr 15 '13 at 14:54

3 Answers3

12

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.

Community
  • 1
  • 1
Francesco Montesano
  • 8,485
  • 2
  • 40
  • 64
2
numpy.concatenate([a[-1:], a[:-1]])
>>> array([4, 0, 1, 2, 3])
Jakub M.
  • 32,471
  • 48
  • 110
  • 179
1

Try this one

b = a[-1:]+a[:-1]
Jan Vorcak
  • 19,261
  • 14
  • 54
  • 90
  • Thanks. Note that I am using numpy arrays so you have to convert to list first... `b=list(a)[-1:]+list(a)[:-1]` – Lee Apr 12 '13 at 11:12
  • ... and I want a numpy array out so `b=np.array(list(a)[-1:]+list(a)[:-1])` – Lee Apr 12 '13 at 11:14