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

前端 未结 6 450
逝去的感伤
逝去的感伤 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:49

    I decided to compare the runtime of the different approaches mentioned here. I've used my library simple_benchmark for this.

    The boolean indexing with array[array != 0] seems to be the fastest (and shortest) solution.

    For smaller arrays the MaskedArray approach is very slow compared to the other approaches however is as fast as the boolean indexing approach. However for moderately sized arrays there is not much difference between them.

    Here is the code I've used:

    from simple_benchmark import BenchmarkBuilder
    
    import numpy as np
    
    bench = BenchmarkBuilder()
    
    @bench.add_function()
    def boolean_indexing(arr):
        return arr[arr != 0]
    
    @bench.add_function()
    def integer_indexing_nonzero(arr):
        return arr[np.nonzero(arr)]
    
    @bench.add_function()
    def integer_indexing_where(arr):
        return arr[np.where(arr != 0)]
    
    @bench.add_function()
    def masked_array(arr):
        return np.ma.masked_equal(arr, 0)
    
    @bench.add_arguments('array size')
    def argument_provider():
        for exp in range(3, 25):
            size = 2**exp
            arr = np.random.random(size)
            arr[arr < 0.1] = 0  # add some zeros
            yield size, arr
    
    r = bench.run()
    r.plot()
    

提交回复
热议问题