1

I am having a slight problem in getting numpy.any() to work fine on my problem. Consider I have a 3D matrix of N X M X M matrix, where I need to get rid of any matrix MXM that has all its elements the same [all zeros to say]. Here is an example to illustrate my issue

x = np.arange(250).reshape(10,5,5)
x[0,:,:] = 0

What I need to do is get rid of the first 5X5 matrix since it contain all zeros. So I tried with

np.any(x,axis=0)

and expected to have a results of

[FALSE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE]

but what i get is

array([[ True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True]
   [ True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True],
   [ True,  True,  True,  True,  True]], dtype=bool)

Applying the follwing results with what I want but I hope that there is a better way without any loops

for i in range(x.shape[0]):
       y.append(np.any(x[i,:,:]))

Did I make a mistake somewhere here? Thanks!

JustInTime
  • 2,716
  • 5
  • 22
  • 25
  • 1
    It may seem that I'm picking at words, but you *can't* have a matrix with more (or less) than 2 dimensions. Your question is valid as a question about arrays (which can have arbitrary dimension.) I wrote a blog post about this: http://wilsonericn.wordpress.com/2011/09/15/the-first-thing-you-should-know-about-matrices/ – Eric Wilson Oct 07 '11 at 12:57

1 Answers1

4

In a 10x5x5 matrix with x[0,:,:] = 0 I would expect a result of:

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

because it is the first of ten 5x5 arrays which is all zero and not of five.

You get this result using

x.any(axis=1).any(axis=1)

or

x.any(axis=2).any(axis=1)

which means you first eliminate the second (axis=1) or the third (asix=2) dimension and then the remaining second (axis=1) and you get the only one dimension, which was originally the first one (axis=0).

eumiro
  • 207,213
  • 34
  • 299
  • 261