Python - NumPy - removing multiple rows and columns from an array

Say I have a square matrix as input :

array([[0, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]) 

I want to count nonzero in the array after deleting rows 2 and 3 and columns 2 and 3. Subsequently, I want to do the same for rows 3 and 4 and columns 3 and 4. Therefore, the output should be:

 0 # when removing rows/cols 2 and 3 3 # when removing rows/cols 3 and 4 

Here is a naive solution using np.delete :

 import numpy as np a = np.array([[0,1,1,0],[1,1,1,1],[1,1,1,1],[0,1,1,0]]) np.count_nonzero(np.delete(np.delete(a, (1,2), axis=0), (1,2), axis=1)) np.count_nonzero(np.delete(np.delete(a, (2,3), axis=0), (2,3), axis=1)) 

But np.delete returns a new array. Is there a faster method that involves deleting rows and columns at the same time? Is it possible to mask? the documentation on np.delete reads:

It is often recommended to use a boolean mask.

How can I do it? Thanks.

+5
source share
2 answers

Instead of deleting columns and rows that you don’t need, it’s easier to select the ones you want. Also note that it is standard to start counting rows and columns from zeros. To get the first example, you must select all the elements in lines 0 and 3 and in lines 0 and 3. This requires advanced indexing , for which you can use the ix_ function :

 In [25]: np.count_nonzero(a[np.ix_([0,3], [0,3])]) Out[25]: 0 

For your second example, you want to select rows 0 and 1 and columns 0 and 1, which can be done using basic slicing :

 In [26]: np.count_nonzero(a[:2,:2]) Out[26]: 3 
+5
source

There is no need to modify the original array by deleting rows / columns in order to count the number of nonzero elements. Just use indexing,

 a = np.array([[0,1,1,0],[1,1,1,1],[1,1,1,1],[0,1,1,0]]) irows, icols = np.indices(a.shape) mask = (irows!=2)&(irows!=3)&(icols!=2)&(icols!=3) np.count_nonzero(a[mask]) 
+3
source

All Articles