hotshotiguana
hotshotiguana

Reputation: 1570

Numpy Advanced Slicing

I am trying to slice the below array to get rows 2 and 3 and the first column in addition to the columns between the 2nd and last columns, but every slice I have tried does not seem to work. For example, the first print statement below gives a syntax error because of the : in the brackets. I have also tried to simply concatenate the arrays, but I don't think this is the most efficient way to accomplish this problem.

import numpy as np
y = np.arange(35).reshape(5, 7)

# My ultimate goal is to do a slice similar to this expression, but this of course gives
# an error. 
print y[[1, 2], [0, 2:-1]]

# This works, but I feel it is inefficient, although I could be wrong.
print np.hstack((y[[1, 2], 0][:, np.newaxis], y[[1, 2], 2:-1]))

Any suggestions would be greatly appreciated.

Upvotes: 1

Views: 1902

Answers (1)

lukecampbell
lukecampbell

Reputation: 15266

I don't know if this is what you're asking for but try

In [11]: y[2:4,[1,3,4,5,6]]
Out[11]: 
array([[15, 17, 18, 19, 20],
       [22, 24, 25, 26, 27]])

In [12]: 

Numpy can be sliced similar to standard Python lists but the dimensions add some trickiness but I still find this solution to be really elegant compared to nesting or looping reshapes but sometimes this will not always be the end-all-be-all solution.

Edit:

It doesn't look good but it's better than a reshape or huge matrix changes

This is the same as saying y[1:3, [0, 2:-1]] without having to reshape the array or iterate through excess elements, you specify the indexes you care about by making a list of [0] + the remaining columns in that dimension.

In [33]: y[1:3, [0] + list(xrange(2,y.shape[1]))]
Out[33]: 
array([[ 7,  9, 10, 11, 12, 13],
       [14, 16, 17, 18, 19, 20]])

Upvotes: 2

Related Questions