简体   繁体   中英

Fast numpy way to multiply non-zero elements in array

Given an array consisting of zeros and positive elements, I want to take the product of the non-zero elements. I am currently replacing zeroes with 1's a[a == 0] = 1 and using np.prod . Given that my array is sparse, one speed up I assume would be to subset for non-zero elements sub = a[a != 0] and take the product over the elements in sub . Is there a more efficient numpy operation to do do this?

Actually, your idea is correct, but it could be shortened to one line code like this:

np.prod(x[x != 0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM