python - 从 NumPy 矩阵中满足条件的每一行中取 N 个第一个值

标签 python arrays numpy matrix mask

我有一个 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

这是一个 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]

方法 #2

灵感来自 NumPy Fancy Indexing - Crop different ROIs from different channels's solution ,我们可以利用 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]

关于python - 从 NumPy 矩阵中满足条件的每一行中取 N 个第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48380129/

相关文章:

python - 如何从带有索引的二维数组中获取值

python - 如何对 pandas 数据框中的一列字符串进行排序,在其中强制按列排序所依据的字母顺序?

java - 有没有更简洁的方法来初始化这个通用数组?

java - java中如何将for循环每次迭代的结果存储到数组中

python - 仅使用 pandas 来填补空白,而不是在末端使用 NaN

python - numpy: "array_like"对象的正式定义?

python - PIL简单渐变和TypeError : an integer is required

python编码utf-8

python - 在 Python 2 中比较时间

javascript - 在javascript中展平数组以获得最长的字符串