I have a numpy vector
, and a numpy array
.
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
and this is my matrix:
[[ 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.]]
the output should be:
[[7,5,None],
[9,8,7],
[21,13,12],
[36,18,11],
[6,6,3],
14,14,13]]
Is there any efficient way to do that with masks or something, without an ugly for
loop?
Any help will be appreciated!
Approach #1
Here's one with
broadcasting
-Approach #2
Inspired by
NumPy Fancy Indexing - Crop different ROIs from different channels
's solution, we can leveragenp.lib.stride_tricks.as_strided
for efficient patch extraction, like so -