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

[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]

Leave a Reply