Filtering out columns with zero values in numpy

Viewed 3699

Given a numpy array A such as:

[[    0.   482.  1900.   961.   579.    56.]
 [    0.   530.  1906.   914.   584.    44.]
 [   43.     0.  1932.   948.   556.    51.]
 [    0.   482.  1917.   946.   581.    52.]
 [    0.   520.  1935.   878.   589.    55.]]

I'd like to get a new array that excludes all columns where a 0 appears, that is:

[[  1900.   961.   579.    56.]
 [  1906.   914.   584.    44.]
 [  1932.   948.   556.    51.]
 [  1917.   946.   581.    52.]
 [  1935.   878.   589.    55.]]

What I've tried is the following:

non_zero = np.array([np.all(totals>0,axis=0)]*N_ROWS);    

Which gives me:

[[False  False  True  True  True  True]
 [False  False  True  True  True  True]
 [False  False  True  True  True  True]
 [False  False  True  True  True  True]
 [False  False  True  True  True  True]]

Trouble is, doing then A[non_zero] returns the expected values but rearranged into a one dimensional vector.

So, do you guys know what I'm doing wrong, or if I'm making life over complicated? Thanks!

UPDATE: thanks for all the answers! One short thing in addition to the accepted answer: clearly, aside from the selection itself, I should have used the : operand as in:

non_zero = np.array(np.all(totals!=0,axis=0));    
a[:,non_zero]

And then of course, there's more compact ways (see accepted answer)

3 Answers
Related