在numpy 2darray中逐行查找值大于阈值的索引

时间:2019-01-28 10:29:11

标签: python numpy threshold numpy-ndarray

我有一个2darray如下。我想按数组中的每一行查找阈值(例如0.7)以上的值的索引。

items= np.array([[1.        , 0.40824829, 0.03210806, 0.29488391, 0.        ,
        0.5       , 0.32444284, 0.57735027, 0.        , 0.5       ],
       [0.40824829, 1.        , 0.57675476, 0.48154341, 0.        ,
        0.81649658, 0.79471941, 0.70710678, 0.57735027, 0.40824829],
       [0.03210806, 0.57675476, 1.        , 0.42606683, 0.        ,
        0.        , 0.92713363, 0.834192  , 0.        , 0.73848549],
       [0.29488391, 0.48154341, 0.42606683, 1.        , 0.        ,
        0.29488391, 0.52620136, 0.51075392, 0.20851441, 0.44232587],
       [0.        , 0.        , 0.        , 0.        , 0.        ,
        0.        , 0.        , 0.        , 0.        , 0.        ],
       [0.5       , 0.81649658, 0.        , 0.29488391, 0.        ,
        1.        , 0.32444284, 0.28867513, 0.70710678, 0.        ],
       [0.32444284, 0.79471941, 0.92713363, 0.52620136, 0.        ,
        0.32444284, 1.        , 0.93658581, 0.22941573, 0.81110711],
       [0.57735027, 0.70710678, 0.834192  , 0.51075392, 0.        ,
        0.28867513, 0.93658581, 1.        , 0.        , 0.8660254 ],
       [0.        , 0.57735027, 0.        , 0.20851441, 0.        ,
        0.70710678, 0.22941573, 0.        , 1.        , 0.        ],
       [0.5       , 0.40824829, 0.73848549, 0.44232587, 0.        ,
        0.        , 0.81110711, 0.8660254 , 0.        , 1.        ]])

indices_items = np.argwhere(items>= 0.7)

此(indices_items)返回

array([[0, 0],
       [1, 1],
       [1, 5],
       [1, 6],
       [1, 7],
       [2, 2],
       [2, 6],
       [2, 7],
       [2, 9],
       [3, 3],
       [5, 1],
       [5, 5],
       [5, 8],
       [6, 1],
       [6, 2],
       [6, 6],
       [6, 7],
       [6, 9],
       [7, 1],
       [7, 2],
       [7, 6],
       [7, 7],
       [7, 9],
       [8, 5],
       [8, 8],
       [9, 2],
       [9, 6],
       [9, 7],
       [9, 9]], dtype=int64)

我如何才能按以下方式获取索引? row0-> [0] row1-> [0,1,5,6,7] row2-> [2,6,7,9] row3-> [3] row4-> []    #此列表应该为空,因为没有超出阈值的值...

2 个答案:

答案 0 :(得分:2)

使用np.where来获取行,然后使用np.searchsorted来获取行数组上的间隔索引并将其用于拆分col数组-

In [38]: r,c = np.where(items>= 0.7)

In [39]: np.split(c,np.searchsorted(r,range(1,items.shape[0])))
Out[39]: 
[array([0], dtype=int64),
 array([1, 5, 6, 7], dtype=int64),
 array([2, 6, 7, 9], dtype=int64),
 array([3], dtype=int64),
 array([], dtype=int64),
 array([1, 5, 8], dtype=int64),
 array([1, 2, 6, 7, 9], dtype=int64),
 array([1, 2, 6, 7, 9], dtype=int64),
 array([5, 8], dtype=int64),
 array([2, 6, 7, 9], dtype=int64)]

答案 1 :(得分:0)

就性能而言,这可能不是最佳选择,但是如果您真的不在乎,应该没问题。

Home[1] = input("How many points did the Rangers score in quarter 2?: ")
IndexError: list assignment index out of range

IndexError: list assignment index out of range
相关问题