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


let's have square matrix input:

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

i want count nonzeros in array after removal of rows 2 , 3 , cols 2 , 3. afterwards want same rows 3 , 4 , cols 3 , 4. hence output should be:

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

here naive solution using np.delete:

import numpy np = 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 new array. there faster method, involves deleting rows , columns simultaneously? can masking used? documentation on np.delete reads:

often preferable use boolean mask.

how go doing that? thanks.

instead of deleting columns , rows don't want, easier select ones want. note standard start counting rows , columns zeros. first example, want select elements in rows 0 , 3 , in rows 0 , 3. requires advanced indexing, can use ix_ utility function:

in [25]: np.count_nonzero(a[np.ix_([0,3], [0,3])])   out[25]: 0 

for second example, want select rows 0 , 1 , columns 0 , 1, can done using basic slicing:

in [26]: np.count_nonzero(a[:2,:2]) out[26]: 3 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -