我想从数组中选择特定范围的索引

aze*_*eez 5 python arrays indexing numpy python-3.x

我有numpy数组,我想根据其索引号选择一些值。我正在使用Python3.6

例如:

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]
Run Code Online (Sandbox Code Playgroud)

因此,如您在上面的示例中所见,我想选择索引号:

if x = 2, 4, 8
Run Code Online (Sandbox Code Playgroud)

如果我只是在x中指定数字,这将起作用,但是如果我想使x变量我尝试例如:

if x:
for i in np.arange(x+2, x-last_index_number, x+2):
return whatever 
Run Code Online (Sandbox Code Playgroud)

其中x + 2 =我想要的第一个索引(起点)。x-last_index_number =我想要的最后一个索引(最后一点)。x + 2 =步骤(我希望它通过在x上加2来继续下一个索引号,依此类推。但这没有用。

所以我的问题是我可以指定要按特定顺序选择的数字:

[5][10][15][20][25][30][35]
or
[4][8][12][16][20]
Run Code Online (Sandbox Code Playgroud)

enu*_*ris 4

Numpy 切片允许您将索引列表输入到数组中,以便您可以切片到所需的精确值。

例如:

    import numpy as np
    a = np.random.randn(10)
    a[[2,4,6,8]]
Run Code Online (Sandbox Code Playgroud)

这将返回第二个、第四个、第六个和第八个数组元素(请记住 python 索引从 0 开始)。因此,如果您想要从索引 x 开始的每个第二个元素,您可以简单地用这些元素填充一个列表,然后将该列表输入到数组中以获得您想要的元素,例如:

    idx = list(range(2,10,2))
    a[idx]
Run Code Online (Sandbox Code Playgroud)

这再次返回所需的元素(索引 2,4,6,8)。