1

Is there an efficient and/or built in function to remove the all-zero rows of a 2d array? I am looking at numpy documentation but I have not found it.

Jon Clements
  • 132,101
  • 31
  • 237
  • 267
Bob
  • 10,159
  • 24
  • 84
  • 136

2 Answers2

4

Boolean indexing will do it:

In [2]:

a
Out[2]:
array([[4, 1, 1, 2, 0, 4],
       [3, 4, 3, 1, 4, 4],
       [1, 4, 3, 1, 0, 0],
       [0, 4, 4, 0, 4, 3],
       [0, 0, 0, 0, 0, 0]])
In [3]:

a[~(a==0).all(1)]
Out[3]:
array([[4, 1, 1, 2, 0, 4],
       [3, 4, 3, 1, 4, 4],
       [1, 4, 3, 1, 0, 0],
       [0, 4, 4, 0, 4, 3]])
CT Zhu
  • 49,083
  • 16
  • 110
  • 125
-1

You can use the built-in function numpy.nonzero.

http://docs.scipy.org/doc/numpy/reference/generated/numpy.nonzero.html

Pythontology
  • 1,384
  • 2
  • 11
  • 15