How can we select more than one element in an array that ar not consecutives?

How can we select more than one element in a numpy array that ar not consecutives?
For instance, on the array below, if we want to choose the 1st the 4th and the 5th, how would we do that?
test_2 = np.array([79, 100, 86, 93, 91])

https://www.codecademy.com/paths/data-science/tracks/intro-statistics-numpy/modules/dspath-intro-numpy/lessons/numpy-introduction/exercises/selecting-elements-1d
#numpy #python #array

1 Like

Assuming you’re only using a limited number of values this way you can just slice it using a list e.g.
desired_vals = test_2[[0, 3, 4]]

This can get a little confusing when dealing with long sequences or multidimensional arrays so only use it when it’s clear and use references to your sequence otherwise. The docs have a bit more detail on indexing but I assume there’s more on this as the lessons continue anyway.
https://docs.scipy.org/doc/numpy/user/basics.indexing.html

2 Likes