19

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.

LWZ
  • 11,670
  • 22
  • 61
  • 79

2 Answers2

54

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])
mgilson
  • 300,191
  • 65
  • 633
  • 696
8

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]

Francesco Montesano
  • 8,485
  • 2
  • 40
  • 64
  • Can you tell me ,why circshift (eye (m), 2) and numpy.roll(numpy.eye(m), -2)) yield different result? – Gunjan naik Sep 02 '15 at 12:36
  • 1
    1.) what is circshift? 2) comments it's not the correct place to ask questions disconnected with the question – Francesco Montesano Sep 02 '15 at 15:06
  • @FrancescoMontesano `circshift` is a [MATLAB function](https://nl.mathworks.com/help/matlab/ref/circshift.html). – Zoltán Csáti May 22 '20 at 09:53
  • I don't know Matlab.My wild guess is: index from 0 or 1; column- vs. row-first ordering; ... – Francesco Montesano May 22 '20 at 10:50
  • @Gunjannaik numpy.roll uses a peculiar default behaviour for 'axis': "By default, the array is flattened before shifting, after which the original shape is restored.". You'll probably need axis=(0,1) to have the behaviour of the two functions match. – Giorgos Sfikas May 17 '22 at 05:15