The main problem associated with the line of code a[~(a==0).all(1)]
is that it works for a numpy.array
and it seems that you are using a numpy.matrix
, for which the code doesn't quite work. If a
is a numpy.matrix
, use instead a[~(a==0).all(1).A1]
.
Since you're new to numpy, I'll point out that complex single lines of code can be better understood by breaking them down into single steps and printing the intermediate results. This is usually the first step of debugging. I'll do this for the line a[~(a==0).all(1)]
for both numpy.array
and numpy.matrix
.
For a numpy.array
:
In [1]: from numpy import *
In [2]: a = 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]: print a==0
[[False False False False True False]
[False False False False False False]
[False False False False True True]
[ True False False True False False]
[ True True True True True True]]
In [6]: print (a==0).all(1)
[False False False False True]
In [7]: print ~(a==0).all(1)
[ True True True True False]
In [8]: print a[~(a==0).all(1)]
[[4 1 1 2 0 4]
[3 4 3 1 4 4]
[1 4 3 1 0 0]
[0 4 4 0 4 3]]
For a numpy.matrix
:
In [1]: from numpy import *
In [2]: a = matrix([[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]: print a==0
[[False False False False True False]
[False False False False False False]
[False False False False True True]
[ True False False True False False]
[ True True True True True True]]
In [5]: print (a==0).all(1)
[[False]
[False]
[False]
[False]
[ True]]
In [6]: print (a==0).all(1).A1
[False False False False True]
In [7]: print ~(a==0).all(1).A1
[ True True True True False]
In [8]: print a[~(a==0).all(1).A1]
[[4 1 1 2 0 4]
[3 4 3 1 4 4]
[1 4 3 1 0 0]
[0 4 4 0 4 3]]
The output of In[5]
shows why this isn't working: (a==0).all(1)
produces a 2D result which can't be used to index the rows. Therefore I just tacked on .A1
in the next line to convert it to 1D.
Here is a good answer on the difference between the arrays and matrices. Also to this I'll add that once the infix operator is fully adopted, there will be almost no advantage to using numpy.matrix
. Also, because most people use numpy.array
s to represent matrices in their code, they will often describe a numpy.array
as a "matrix", thus creating confusion in the terminology.
Finally, as an aside I'll note that all of the above was done in ipython from the command line. IPython is an excellent tool for this type of work.