Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to select specific range of indexes from an array

I have numpy array, and I want to select a number of values based on their index number. I am using Python3.6

for example:

np.array:
index#
[0]
[1]  + + + + + + + + + +         + + + + + + + + + +
[2]  + I want to selct +         + I don't want to select:
[3]  + the indexs:     +         +                  [0]
[4]  +      [2]        +         +                  [10]
[5]  +      [4]        +         +       Or any between
[6]  +      [6]        +         + 
[7]  +      [8]        +         + + + + + + + + + +
[8]  + + + + + + + + + +
[9]
[10]

so as you can see for the example above I want to select the index number:

if x = 2, 4, 8

this will work if I just specify the numbers in x but if I want to make x variable I tried for example:

if x:
for i in np.arange(x+2, x-last_index_number, x+2):
return whatever 

Where x+2 = the first index I want (the start point). x-last_index_number = the last index I want (the last point). x+2 = the step (I want it to go the next index number by adding 2 to x and so on. but this didn't work.

So my question can I specify numbers to select in a certain order:

[5][10][15][20][25][30][35]
or
[4][8][12][16][20]
like image 995
azeez Avatar asked Dec 14 '17 22:12

azeez


People also ask

How do you specify an array range?

A range of array variables can be indicated by separating the first array index value from the last index value by two decimal points.

How do you select a specific range of an array in Python?

To select an element from Numpy Array , we can use [] operator i.e. It will return the element at given index only.

How do I extract an index from an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

What is range of index in array?

The elements of array InputData are INTEGERs and the indices are in the range of 0 and 100.


1 Answers

Numpy slicing allows you to input a list of indices to an array so that you can slice to the exact values you want.

For example:

    import numpy as np
    a = np.random.randn(10)
    a[[2,4,6,8]]

This will return the 2nd, 4th, 6th, and 8th array elements (keeping in mind that python indices start from 0). So, if you want every 2nd element starting from an index x, you can simply populate a list with those elements and then feed that list into the array to get the elements you want, e.g:

    idx = list(range(2,10,2))
    a[idx]

This again returns the desired elements (index 2,4,6,8).

like image 183
enumaris Avatar answered Sep 22 '22 05:09

enumaris