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

Identifying deleted rows and columns of an array in Python

I have an array A1. I am deleting the zero rows and columns but I also want to identify which row and column was deleted. I present the current and expected output.

import numpy as np

        
A1=np.array([[0, 1, 2],
            [0, 0, 0],
            [0, 3, 4]])

mask = A1!= 0
A2 = A1[np.ix_(mask.any(1), mask.any(0))]
print([A2])

The current output is

[array([[1, 2],
       [3, 4]])]

The expected output is

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

[array([[1, 2],
       [3, 4]])]
[1] where 1 is the deleted row, 
[0] where 0 is the deleted column  

>Solution :

This is the code for get your desired output:

import numpy as np

A1=np.array([[0, 1, 2],
            [0, 0, 0],
            [0, 3, 4]])

mask = A1 != 0
deleted_rows = np.where(~mask.any(axis=1))[0]
deleted_columns = np.where(~mask.any(axis=0))[0]
A2 = A1[np.ix_(mask.any(1), mask.any(0))]

print([A2])
print("Deleted rows:", deleted_rows)
print("Deleted columns:", deleted_columns)

Result:

array([[1, 2],
       [3, 4]])]
Deleted rows: [1]
Deleted columns: [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