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 this possible? I know that to extract the first three numbers you simply do x[:3]
and to extract the last four you do x[-4:]
, but is there a simple way of extracting all that in a simple slice? I know this can be done by, e.g., appending both calls,
>>> y = numpy.append(x[:3],x[-4:])
but I was wondering if there is some simple little trick to do it in a more direct, pythonic way, without having to reference x
again (i.e., I first thought that maybe x[-4:3]
could work but I realized immediately that it didn't made sense).
To remove an element from a NumPy array: Specify the index of the element to remove. Call the numpy. delete() function on the array for the given index.
One-Dimensional SlicingThe first item of the array can be sliced by specifying a slice that starts at index 0 and ends at index 1 (one item before the 'to' index). Running the example returns a subarray with the first element. We can also use negative indexes in slices.
To slice elements from two-dimensional arrays, you need to specify both a row index and a column index as [row_index, column_index] . For example, you can use the index [1,2] to query the element at the second row, third column in precip_2002_2013 .
I think you should use index arrays.
indices = list(range(3))+list(range(-4,0))
y = x[indices]
You can probably drop list
casts (not sure because python 3 changed the behaviour a bit). Or you could use numpy
range genreators.
Edit: not sure why the downvote, cause it works:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With