python - Selecting specific rows and columns from NumPy array -


i've been going crazy trying figure out stupid thing i'm doing wrong here.

i'm using numpy, , have specific row indices , specific column indices want select from. here's gist of problem:

import numpy np  = np.arange(20).reshape((5,4)) # array([[ 0,  1,  2,  3], #        [ 4,  5,  6,  7], #        [ 8,  9, 10, 11], #        [12, 13, 14, 15], #        [16, 17, 18, 19]])  # if select rows, works print a[[0, 1, 3], :] # array([[ 0,  1,  2,  3], #        [ 4,  5,  6,  7], #        [12, 13, 14, 15]])  # if select rows , single column, works print a[[0, 1, 3], 2] # array([ 2,  6, 14])  # if select rows , columns, fails print a[[0,1,3], [0,2]] # traceback (most recent call last): #   file "<stdin>", line 1, in <module> # valueerror: shape mismatch: objects cannot broadcast single shape 

why happening? surely should able select 1st, 2nd, , 4th rows, , 1st , 3rd columns? result i'm expecting is:

a[[0,1,3], [0,2]] => [[0,  2],                       [4,  6],                       [12, 14]] 

fancy indexing requires provide indices each dimension. providing 3 indices first one, , 2 second one, hence error. want this:

>>> a[[[0, 0], [1, 1], [3, 3]], [[0,2], [0,2], [0, 2]]] array([[ 0,  2],        [ 4,  6],        [12, 14]]) 

that of course pain write, can let broadcasting you:

>>> a[[[0], [1], [3]], [0, 2]] array([[ 0,  2],        [ 4,  6],        [12, 14]]) 

this simpler if index arrays, not lists:

>>> row_idx = np.array([0, 1, 3]) >>> col_idx = np.array([0, 2]) >>> a[row_idx[:, none], col_idx] array([[ 0,  2],        [ 4,  6],        [12, 14]]) 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -