Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Forward fill Numpy matrix / mask with values based on condition

I have the following matrix

import numpy as np


A = np.array([
    [0, 0, 0, 0, 1, 0, 1],
    [0, 0, 0, 0, 0, 0, 1],
    [1, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0]
]).astype(bool)

How do I fill all the rows column-wise after a column is True?

My desired output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    [0, 0, 0, 0, 1, 1, 1],
    [0, 0, 0, 0, 0, 0, 1],
    [1, 1, 1, 1, 1, 1, 1],
    [0, 0, 0, 0, 0, 0, 0]

>Solution :

You could use logical_or combined with accumulate:

np.logical_or.accumulate(A, axis=1)

Output:

array([[False, False, False, False,  True,  True,  True],
       [False, False, False, False, False, False,  True],
       [ True,  True,  True,  True,  True,  True,  True],
       [False, False, False, False, False, False, False]])

If you want integers, go with maximum:

np.maximum.accumulate(A.astype(int), axis=1)

array([[0, 0, 0, 0, 1, 1, 1],
       [0, 0, 0, 0, 0, 0, 1],
       [1, 1, 1, 1, 1, 1, 1],
       [0, 0, 0, 0, 0, 0, 0]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading