【问题标题】:selecting rows in numpy ndarray based on the value of two columns根据两列的值选择numpy ndarray中的行
【发布时间】:2014-06-15 02:37:06
【问题描述】:

我有一个很大的np.ndarray (3600000,3)HUEVALUE 和一个关联的CLASS 号码。对于每对HUEVALUE,我想使用这个数组找到对应的Class 数字。我是 Python 的初学者,很难做到。你知道一种方法吗?

提前谢谢你!

【问题讨论】:

    标签: python numpy multidimensional-array


    【解决方案1】:

    我假设你的数组看起来像:

           |(HUE)(VALUE)(CLASS)
    row/col|   0     1     2
    -------+-----------------
    0      |   0     1     2
    1      |   3     4     5
    2      |   6     7     8
    .      |   .     .     .
    .      |   .     .     .
    3599999|   .     .     .
    

    这里是示例代码。为简单起见,我将大小 3600000 更改为 5。

    a = np.array(xrange(5 * 3))
    a.shape = (5, 3)
    

    现在数组a 看起来像这样:

    array([[ 0,  1,  2],
           [ 3,  4,  5],
           [ 6,  7,  8],
           [ 9, 10, 11],
           [12, 13, 14]])
    

    如果你想要HUE=9 的行,这样做:

    a[np.where(a[:,0] == 9)]
    #array([[ 9, 10, 11]])
    

    如果你想要VALUE=4 的行,这样做:

    a[np.where(a[:,1] == 4)]
    #array([[3, 4, 5]])
    

    如果你想要HUE=0VALUE=1 的行,这样做:

    a[np.where((a[:,0] == 0) * (a[:,1] == 1))]
    #array([[0, 1, 2]])
    

    【讨论】:

    • HUE=1VALUE=1 怎么样?
    【解决方案2】:

    试试这个代码:

     x[x[:, 2] == class_number[:, :2]
    

    其中xnp.ndarray

     x[:, 2] == class_number
    

    包含true/false,表示最后一个是否为class_number

    你需要看看:Boolean indexing in http://wiki.scipy.org/Cookbook/Indexing

    从评论中移出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-26
      • 2015-08-15
      • 1970-01-01
      相关资源
      最近更新 更多