从满足条件的NumPy矩阵的每一行中获取N个第一值 [英] Take N first values from every row in NumPy matrix that fulfill condition

查看:261
本文介绍了从满足条件的NumPy矩阵的每一行中获取N个第一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy vector和一个numpy array.

我需要从矩阵的每一行中获取前N个(让我们说3个)值,这些值小于(或等于)向量中的相应行.

I need to take from every row in the matrix the first N (lets say 3) values that are smaller than (or equal to) the corresponding line in the vector.

所以如果这是我的载体:

so if this is my vector:

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循环的情况下,有没有任何有效的方法可以使用面具或类似的东西来做到这一点?

Is there any efficient way to do that with masks or something, without an ugly for loop?

任何帮助将不胜感激!

推荐答案

方法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解决方案的启发,我们可以利用

Inspired by NumPy Fancy Indexing - Crop different ROIs from different channels's solution, we can leverage np.lib.stride_tricks.as_strided for efficient patch extraction, like so -

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]

这篇关于从满足条件的NumPy矩阵的每一行中获取N个第一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆