a and b are 1 dimensional numpy arrays (or python lists):
I am doing this:
>>> c = [x/y for x,y in zip(a,b)]
Occasionally b has a zero in it - so a division by zero error occurs.
How can I conditionally check for a 0 value in b and set the corresponding element of c to 0?
You can use if-else condition inside list comprehension:
>>> c = [x/y if y else 0 for x,y in zip(a,b)]
You can use a ternary expression inside the list comprehension:
[x/y if y!= 0 else 0 for x,y in zip(a,b)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With