Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy slice from beginning and from end

Tags:

python

numpy

array = numpy.array([1,2,3,4,5,6,7,8,9,10])
array[-1:3:1]
>> []

I want this array indexing to return something like this:

[10,1,2,3]
like image 968
Nurislam Fazulzyanov Avatar asked Jun 05 '26 12:06

Nurislam Fazulzyanov


2 Answers

np.roll lets you wrap an array which might be useful

import numpy as np

a = np.array([1,2,3,4,5,6,7,8,9,10])

b = np.roll(a,1)[0:4]

results in

>>> b
array([10  1  2  3])
like image 135
Grant Williams Avatar answered Jun 08 '26 00:06

Grant Williams


Use np.roll to:

Roll array elements along a given axis. Elements that roll beyond the last position are re-introduced at the first.

>>> np.roll(x, 1)[:4]
array([10,  1,  2,  3])
like image 34
user3483203 Avatar answered Jun 07 '26 22:06

user3483203



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!