【问题标题】:I want to select specific range of indexes from an array我想从数组中选择特定范围的索引
【发布时间】:2018-05-29 03:10:16
【问题描述】:

我有 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]

如上例所示,我想选择索引号:

if x = 2, 4, 8

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

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

在哪里 x+2 = 我想要的第一个索引(起点)。 x-last_index_number = 我想要的最后一个索引(最后一点)。 x+2 = 步骤(我希望它通过将 2 添加到 x 等来进入下一个索引号。 但这不起作用。

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

[5][10][15][20][25][30][35]
or
[4][8][12][16][20]

【问题讨论】:

标签: python arrays python-3.x numpy indexing


【解决方案1】:

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

例如:

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

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

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

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

【讨论】:

    【解决方案2】:

    你的 x 是一个长度为 20 的数组

    x = np.arange(0,20)
    

    返回

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

    访问每个第 n 个(此处为偶数索引)元素,忽略数组 x 中的前两个和后两个索引

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

    返回

    [2 4 6 8]
    

    其余的以类似的方式,

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

    返回

    [ 5 10 15]
    [ 4  8 12 16]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 2018-05-02
      • 2014-04-28
      • 1970-01-01
      相关资源
      最近更新 更多