How do I remove all zero elements from a NumPy array?

ruben baetens picture ruben baetens · May 8, 2011 · Viewed 91.6k times · Source

I have a rank-1 numpy.array of which I want to make a boxplot. However, I want to exclude all values equal to zero in the array. Currently, I solved this by looping the array and copy the value to a new array if not equal to zero. However, as the array consists of 86 000 000 values and I have to do this multiple times, this takes a lot of patience.

Is there a more intelligent way to do this?

Answer

Sven Marnach picture Sven Marnach · May 8, 2011

For a NumPy array a, you can use

a[a != 0]

to extract the values not equal to zero.