Home > Back-end >  Selecting Elements in a one dimensional array in Python Numpy
Selecting Elements in a one dimensional array in Python Numpy

Time:04-11

I have created a one dimensional array in Pyhton Numpy as follows:

import numpy as np
list1=[573, 554, 536, 535, 531, 523, 521, 519, 518, 518, 515, 514, 511, 506, 504, 501, 501, 500, 500, 499, 495, 494, 493, 491, 490, 489, 487, 485, 484, 482, 482, 481, 479, 478, 477, 471, 466, 453, 449, 448, 445, 439, 434, 432, 427, 423, 421, 413, 410, 409, 407, 394, 391, 388, 388, 386, 376, 376, 375, 368]
array_example = np.array(list1)

Now I would like to select the 3rd, 7th and 9th value so I get the values 536, 521, 518.

I try:

array_example[2,6,8]

but get the following error:

---------------------------------------------------------------------------
IndexError  Traceback (most recent call last)
<ipython-input-4-6335bacdceb1> in <module>
----> 1 array_example[2,6,8]
IndexError: too many indices for array: array is 1-dimensional, but 3 were indexed

What would be the right solution? Any suggestions? Ty in advance!

CodePudding user response:

Try this:

array_example[[2,6,8]]

It is called 'fancy indexing'.

  • Related