Well, you basically add c/nonzeros to the tmp array in the broadcast, except where the tmp element is zero. Thus, one way would be to save the 0s upfront mask, add to c/nonzeros and finally use the mask for the reset tmp elements.
Therefore, the implementation will be -
mask = tmp==0 tmp+= c/nonzeros tmp[mask] = 0
Runtime test
Approaches -
# @DSM soln def fast(tmp, c, nonzeros): return tmp + np.where(tmp > 0, c/nonzeros, 0)
Dates -
In [341]:
Shorter alternative
If you are looking for compact code, here is another, using a non-0s mask to do a translation using elementary multiplication with c/nonzeros and add to tmp and therefore have a one-line solution, like
tmp += (tmp!=0)*(c/nonzeros)
Note. . To avoid dividing by 0 , we could edit nonzeros by 0s with anything other than 0 , say 1 , and then use the published approaches, as well -
nonzeros = np.where(nonzeros > 0, nonzeros, 1)
source share