从满足条件的 NumPy 矩阵的每一行中获取前 N 个值。

5

我有一个 numpy向量 和一个 numpy数组

我需要从矩阵的每一行中取出前 N 个(比如说 3 个)小于(或等于)向量相应行的值。

如果我的向量是这样的:

7,
9,
22,
38,
6,
15

这是我的矩阵:

[[ 20.,   9.,   7.,   5.,   None,   None],
 [ 33.,  21.,  18.,   9.,   8.,   7.],
 [ 31.,  21.,  13.,  12.,   4.,   0.],
 [ 36.,  18.,  11.,   7.,   7.,   2.],
 [ 20.,  14.,  10.,   6.,   6.,   3.],
 [ 14.,  14.,  13.,  11.,   5.,   5.]]

输出应该是:

[[7,5,None],
 [9,8,7],
 [21,13,12],
 [36,18,11],
 [6,6,3],
 14,14,13]]

有没有一种高效的方法可以使用掩码或其他方式来完成,而不需要使用丑陋的for循环?
任何帮助都将不胜感激!

1
它是否总是按行降序排序? - Divakar
好的观点,在我的情况下,是的。而且None总是出现在最后。 - Binyamin Even
1个回答

3

方法一

这是一种利用broadcasting的方法 -

def takeN_le_per_row_broadcasting(a, b, N=3): # a, b : 1D, 2D arrays respectively
    # First col indices in each row of b with <= corresponding one in a
    idx = (b <= a[:,None]).argmax(1)

    # Get all N ranged column indices
    all_idx = idx[:,None] + np.arange(N)

    # Finally advanced-index with those indices into b for desired output
    return b[np.arange(len(all_idx))[:,None], all_idx]

方法二

NumPy Fancy Indexing - Crop different ROIs from different channels的解决方案启发,我们可以利用np.lib.stride_tricks.as_strided来实现有效的补丁提取,如下所示 -

from skimage.util.shape import view_as_windows

def takeN_le_per_row_strides(a, b, N=3): # a, b : 1D, 2D arrays respectively
    # First col indices in each row of b with <= corresponding one in a
    idx = (b <= a[:,None]).argmax(1)

    # Get 1D sliding windows for each element off data
    w = view_as_windows(b, (1,N))[:,:,0]

    # Use fancy/advanced indexing to select the required ones
    return w[np.arange(len(idx)), idx]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接