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

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

    You can index with a Boolean array. For a NumPy array A:

    res = A[A != 0]
    

    You can use Boolean array indexing as above, bool type conversion, np.nonzero, or np.where. Here's some performance benchmarking:

    # Python 3.7, NumPy 1.14.3
    
    np.random.seed(0)
    
    A = np.random.randint(0, 5, 10**8)
    
    %timeit A[A != 0]          # 768 ms
    %timeit A[A.astype(bool)]  # 781 ms
    %timeit A[np.nonzero(A)]   # 1.49 s
    %timeit A[np.where(A)]     # 1.58 s
    

提交回复
热议问题