您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

这是一个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]
其他 2022/1/1 18:34:21 有514人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶