Skip to content
Advertisement

How to get NumPy array of n last/first Trues in each row

I have a broadcasted array, which is sorted rowly, and a masked array. I want to get the last n elements (or the first n ones) of each row which are True i.e.:

JavaScript

Do we have to split the array (using np.cumsum(np.sum(mask, axis=1))), pad and …?
What will be the best way to do this just with NumPy?

Advertisement

Answer

Using numpy to get the first n True:

JavaScript

Output:

JavaScript

Last n:

JavaScript

Output:

JavaScript

NB. There must be at least n True per row to have the correct final shape

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement