代码之家  ›  专栏  ›  技术社区  ›  Aeolai

从numpy数组中提取数据子集

  •  0
  • Aeolai  · 技术社区  · 5 年前

    E、 g.给定数组[[1,5],[2,6],[3,7],[4,8]],我想提取第二列高于6的所有行,因此得到[3,7],[4,8]。

    3 回复  |  直到 5 年前
        1
  •  2
  •   s3dev    5 年前

    a[a[:,1] > 6]
    

    输出:

    array([[3, 7], [4, 8]])
    

    在哪里? a

        2
  •  1
  •   Oli    5 年前

    使用 numpy.where :

    import numpy as np
    
    a = np.array([[1, 5], [2, 6], [3, 7], [4, 8]])
    # all elements where the second item it greater than 6:
    print(a[np.where(a[:, 1] > 6)])
    # output: [[3 7], [4 8]]
    
        3
  •  1
  •   frab    5 年前

    使用列表理解:

    array1 = [[1, 5], [2, 6], [3, 7], [4, 8]]
    
    threshold = 6
    print([elem for elem in array1 if elem[1] > threshold])
    # [[3, 7], [4, 8]]
    

    import numpy as np
    
    array1 = np.array(array1)
    print(array1[array1[:,1] > 6])
    # array([[3, 7], [4, 8]])