How do you rotate the numbers in an numpy array of shape (n,) or (n,1)?

numpy, python

Solution

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.

Problem

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) ```

Original source

Related problems