Bin*_*ven 5 python arrays numpy mask matrix
我有一个numpy vector,一个numpy array.
我需要从矩阵中的每一行获取小于(或等于)向量中相应行的第一个N(比如3)值.
所以如果这是我的载体:
7,
9,
22,
38,
6,
15
Run Code Online (Sandbox Code Playgroud)
这是我的矩阵:
[[ 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.]]
Run Code Online (Sandbox Code Playgroud)
输出应该是:
[[7,5,None],
[9,8,7],
[21,13,12],
[36,18,11],
[6,6,3],
14,14,13]]
Run Code Online (Sandbox Code Playgroud)
是否有任何有效的方法来做掩码或其他东西,没有丑陋的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]
Run Code Online (Sandbox Code Playgroud)
方法#2
受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]
Run Code Online (Sandbox Code Playgroud)