I want to select specific range of indexes from an array

34,839

Solution 1

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).

Solution 2

Your x is an array of length 20

x = np.arange(0,20)

Returns

x [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]

Access every nth(even indices here) element ignoring first two and last two indices in the array x by

print(x[2:len(x)-1:2])

Returns

[2 4 6 8]

And for the rest in similar fashion,

print(x[5:len(x)-1:5])
print(x[4:len(x)-1:4])

Returns

[ 5 10 15]
[ 4  8 12 16]
Share:
34,839
azeez
Author by

azeez

Updated on December 15, 2020

Comments

  • azeez
    azeez over 3 years

    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]