python - Numpy Advanced Indexing with 1D array -


so given 1d array like

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

i want index multiple elements @ same time. example instead of

x[1] x[2] 

i want use

x[(1,2)] traceback (most recent call last): file "<stdin>", line 1, in <module> indexerror: many indices array 

it works 1 2d array example

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

so can see, nd-arrays works fine! way kind of indexing 1d-arrays?

you need wrap indices in list, not tuple: x[[1,2]]. triggers advanced indexing , numpy returns new array values @ indices you've written.


whenever possible, numpy implicitly assumes each element of tuple indexes different dimension of array. array has 1 dimension, not 2, hence x[(1,2)] raises error.

the reason x[(1,2), :] succeeds 2d array you've explicitly told numpy array has (at least) 2 dimensions , said want first 2 axes. index parsed 2-tuple ((1,2), :) (1,2) instead used advanced indexing along first axis. had used x[(1,2)] or x[1,2], single element @ row 1, column 2.

parsing index complicated numpy because (unlike python) there several different indexing methods can used. complicate things further, different methods may used on different axes! can study exact implementation in numpy's mapping.c file.


Comments

Popular posts from this blog

searchKeyword not working in AngularJS filter -

sequelize.js - Sequelize: sort by enum cases -

user interface - how to replace an ongoing process of image capture from another process call over the same ImageLabel in python's GUI TKinter -