如何从NumPy数组中删除所有零元素? [英] How do I remove all zero elements from a NumPy array?

查看:3566
本文介绍了如何从NumPy数组中删除所有零元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个等级1 numpy.array,我想制作一个箱线图.但是,我想排除数组中所有等于零的值.目前,我通过循环数组解决了这个问题,如果不等于零,则将值复制到新数组中.但是,由于数组由86 000 000个值组成,并且我必须多次执行此操作,因此需要大量的耐心.

I have a rank-1 numpy.array of which I want to make a boxplot. However, I want to exclude all values equal to zero in the array. Currently, I solved this by looping the array and copy the value to a new array if not equal to zero. However, as the array consists of 86 000 000 values and I have to do this multiple times, this takes a lot of patience.

有没有更聪明的方式来做到这一点?

Is there a more intelligent way to do this?

推荐答案

在这种情况下,您要使用带掩码的数组,它保持数组的形状,并且所有numpy和matplotlib函数都会自动识别它. >

This is a case where you want to use masked arrays, it keeps the shape of your array and it is automatically recognized by all numpy and matplotlib functions.

X = np.random.randn(1e3, 5)
X[np.abs(X)< .1]= 0 # some zeros
X = np.ma.masked_equal(X,0)
plt.boxplot(X) #masked values are not plotted

#other functionalities of masked arrays
X.compressed() # get normal array with masked values removed
X.mask # get a boolean array of the mask
X.mean() # it automatically discards masked values

这篇关于如何从NumPy数组中删除所有零元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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