2

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?

Lee
  • 29,398
  • 28
  • 117
  • 170

4 Answers4

10

You can use if-else condition inside list comprehension:

>>> c = [x/y if y else 0 for x,y in zip(a,b)]
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
8

You can use a ternary expression inside the list comprehension:

[x/y if y!= 0 else 0 for x,y in zip(a,b)]
mgilson
  • 300,191
  • 65
  • 633
  • 696
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
2

It seems that numpy does what you want by default:

>>> a = np.array([1,2,3])
>>> b = np.array([0,1,3])
>>> a / b
array([0, 2, 1])

As @Jaime pointed out, if at least one array is of type float, then division by 0 results in inf, so you need to do this:

>>> a = np.array([1,2,3], dtype='float')
>>> b = np.array([0,1,3], dtype='float')
>>> c = a / b
>>> c
array([ inf,   2.,   1.])
>>> c[c == np.inf] = 0
>>> c
array([ 0.,  2.,  1.])
Akavall
  • 82,592
  • 51
  • 207
  • 251
  • 3
    Actually, if either of your arrays is of type float, it will place an `inf` at every position where a division by zero happens. – Jaime Jun 27 '13 at 16:23
1

The old syntax:

[y and x/y or 0 for x, y in zip(a, b)]

The new syntax:

[x/y if y else 0 for x, y in zip(a, b)]

It should be noted that numpy handles this perfectly by itself:

numpy.arange(-3, 7, dtype='float') / numpy.arange(-5, 5, dtype='float')

array([ 0.6       ,  0.5       ,  0.33333333, -0.        , -1.        ,
               inf,  3.        ,  2.        ,  1.66666667,  1.5       ])
Wolph
  • 78,177
  • 11
  • 137
  • 148
  • In this case, I think you could get away with just `y and x/y for x,y in zip(a,b)` ... But that's quite tricky to parse :) – mgilson Jun 27 '13 at 14:01
  • You're right, didn't even think about that :) But for the sake of readability I'll leave it – Wolph Jun 27 '13 at 14:01