11

I have a numpy array like this:

x=np.array([0,1,2,3,4])

and want to create an array where the value in index 0 is in index 1, index 1 is in index 2, etc.

The output I want is:

y=np.array([0,0,1,2,3]).

I'm guessing there's an easy way to do this without iterating through the full array. How can I do this in a numPythonic way?

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
Idr
  • 6,000
  • 6
  • 34
  • 49

2 Answers2

17

You can use

y = numpy.roll(x, 1)
y[0] = 0

or

y = numpy.r_[0, x[:-1]]
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
3

If you wanted to do this in-place, you could also do:

x[1:] = x[:-1]
x[0] = 0
1''
  • 26,823
  • 32
  • 143
  • 200