Pythonic way to cut part of a numpy array

Suppose you have the following numpy array,

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

and you want to extract a new numpy array consisting of only the first three (3) and last four (4) elements, i.e.

 >>> y = x[something] >>> print y [0 1 2 7 8 9 10] 

Is it possible? I know that to extract the first three numbers you just do x[:3] and to extract the last four you do x[-4:] , but is there an easy way to extract all this into a simple fragment? I know that this can be done, for example, by adding both calls,

  >>> y = numpy.append(x[:3],x[-4:]) 

but I was wondering if there was any simple trick to make it more direct, Putin's way, without having to refer to x again (that is, I thought at first that maybe x[-4:3] might work , but I immediately realized that it did not make sense).

+7
python arrays numpy
source share
3 answers

I think you should use arrays of indexes .

 indices = list(range(3))+list(range(-4,0)) y = x[indices] 

You can probably opt out of list butts (not sure because python 3 changed the behavior a bit). Or you can use numpy range animators.

Edit: not sure why downvote is causing it to work :

 import numpy x = numpy.array([0,1,2,3,4,5,6,7,8,9,10]) indices = list(range(3))+list(range(-4,0)) y = x[indices] print(y) 
+2
source share

A simple slice probably won't work. You can use numpy extended slicing:

 >>> import numpy as np >>> a = np.arange(10) >>> something = [0, 1, 2, -4, -3, -2, -1] >>> a[something] array([0, 1, 2, 6, 7, 8, 9]) 

Notice that I went through the list of indexes that I wanted to take from the original array ...

Honestly, your solution with np.append is probably just as good ...

+4
source share
 np.arange(11)[np.r_[0:3,7:11]] # array([ 0, 1, 2, 7, 8, 9, 10]) 

np.r_ is a function, actually an indexed object, in numpy/lib/index_tricks . It takes several fragments or indexes and combines them into one indexing array.

 np.r_[0:3,7:11] # array([ 0, 1, 2, 7, 8, 9, 10]) 

Or borrowing from luk32 answer, a negative slice works:

 a[np.r_[:3,-4:0]] 

An alternative to splicing two parts is to remove the middle. s_ allows you to use slice notation inside a function.

 np.delete(np.arange(11),np.s_[3:7]) # array([ 0, 1, 2, 7, 8, 9, 10]) 

Take a look at the code for the .lib.index_tricks , delete and insert functions for more ideas on how to create index arrays from multiple parts.

Sometimes a logical index is convenient. Make everything True or False and flip the selected items.

 i = np.ones(a.shape,dtype='bool') i[3:7] = False a[i] 
+1
source share

All Articles