Perform numpy product over non-zero elements of a row

Viewed 548

I have a 2d array r. What I want to do is to take the product of each row (excluding the zero elements in that row). For example if I have:

r = [[1 2 0 3 4],
     [0 2 5 0 1],
     [1 2 3 4 0]]

Then what I want is to have another 2d array result such that:

result = [[24],
          [10],
          [24]]

How can I achieve this using numpy.prod?

1 Answers

I think I figured it out:

np.prod(r, axis = 1, where = r > 0, keepdims = True)

Output:

array([[24],                                                                                                                   
[10],                                                                                                                   
[24]]) 
Related