How do I remove all zero elements from a NumPy array?

前端 未结 6 464
逝去的感伤
逝去的感伤 2020-12-24 07:14

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 loo

6条回答
  •  悲哀的现实
    2020-12-24 07:36

    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
    

提交回复
热议问题