Nurislam Fazulzyanov
Nurislam Fazulzyanov

Reputation: 181

Numpy slice from beginning and from end

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]

Upvotes: 3

Views: 3050

Answers (5)

Paul Panzer
Paul Panzer

Reputation: 53109

Use np.r_:

import numpy as np
>>> 
>>> arr = np.arange(1, 11)
>>> arr[np.r_[-1:3]]
array([10,  1,  2,  3])

Upvotes: 3

anishtain4
anishtain4

Reputation: 2412

As one of the answers mentioned, rolling the array makes a copy of the whole array which can be memory consuming for large arrays. So just another way of doing this without converting to list is:

np.concatenate([array[-1:],array[:3]])

Upvotes: 3

user3483203
user3483203

Reputation: 51185

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

Upvotes: 4

Zionsof
Zionsof

Reputation: 1256

Simplest solution would be to convert first to list, and then join and return to array.

As such:

>>> numpy.array(list(array[-1:]) + list(array[:3]))
array([10,  1,  2,  3])

This way you can choose which indices to start and end, without creating a duplicate of the entire array

Upvotes: -1

Grant Williams
Grant Williams

Reputation: 1537

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

Upvotes: 4

Related Questions