Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I slice a numpy array to get both the first and last two rows

Tags:

python

numpy

As far as I can see it, it isn't covered in the indexing, slicing and iterating scipy tutorial, so let me ask it here:

Say I've

x = np.array([[1,2],[3,4],[5,6],[7,8],[9,0]])
x: array([[1, 2],
          [3, 4],
          [5, 6],
          [7, 8],
          [9, 0]])

How do I slice the array in order get both the first and last rows:

y: array([[1, 2],
          [3, 4],              
          [7, 8],
          [9, 0]])
like image 483
Mattijn Avatar asked Apr 02 '14 00:04

Mattijn


People also ask

Can you slice NumPy arrays?

Slicing in python means extracting data from one given index to another given index, however, NumPy slicing is slightly different. Slicing can be done with the help of (:) . A NumPy array slicing object is constructed by giving start , stop , and step parameters to the built-in slicing function.

How do I split a NumPy array horizontally?

hsplit() function. The hsplit() function is used to split an array into multiple sub-arrays horizontally (column-wise). hsplit is equivalent to split with axis=1, the array is always split along the second axis regardless of the array dimension.

How do I slice in NumPy?

Slice Two-dimensional Numpy Arrays 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 .

How do you split an array into two parts in Python?

Use the array_split() method, pass in the array you want to split and the number of splits you want to do.


1 Answers

I don't know if there's a slick way to do that. You could list the indices explicitly, of course:

>>> x[[0,1,-2,-1]]
array([[1, 2],
       [3, 4],
       [7, 8],
       [9, 0]])

Or use r_ to help, which would probably be more convenient if we wanted more rows from the head or tail:

>>> x[np.r_[0:2, -2:0]]
array([[1, 2],
       [3, 4],
       [7, 8],
       [9, 0]])
like image 134
DSM Avatar answered Sep 20 '22 12:09

DSM