I am having a slight problem in getting numpy.any() to work fine on my problem. Consider I have a 3D matr开发者_JS百科ix 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!
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).
精彩评论