对于numpy.any,需要对矩阵进行少量说明 [英] Small clarification needed on numpy.any for matrices

查看:144
本文介绍了对于numpy.any,需要对矩阵进行少量说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让numpy.any()在我的问题上正常工作时,我遇到了一个小问题. 考虑我有一个N X M X M矩阵的3D矩阵,在这里我需要摆脱所有元素都相同的矩阵MXM [都用零表示]. 这是一个示例来说明我的问题

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

我需要做的是摆脱第一个5X5矩阵,因为它包含全零. 所以我尝试了

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)

,预期结果为

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

但是我得到的是

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!

推荐答案

在具有x[0,:,:] = 0的10x5x5矩阵中,我希望得到以下结果:

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

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

因为这是 10 个5x5数组中的第一个,全为零,而不是 5 .

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)

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

这意味着您首先消除第二个(轴= 1)或第三个(轴= 2)维,然后消除其余的第二个(轴= 1),然后获得唯一的一个维,该维最初是第一个(轴) = 0).

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).

这篇关于对于numpy.any,需要对矩阵进行少量说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆