问题
I have two lists a
and b
of equal length. I want to calculate the sum of their ratio:
c = np.sum(a/b)
how can I have a zero (0) value in the summation coefficient when there is division by zero?
EDIT: Here a couple of answers I tested for my case, and still raise the error. Probably I am missing something. The aray that contains zero elements is counts
:
try:
cnterr = (counts/np.mean(counts))*(((cnterr/counts)**2 + (meanerr/np.mean(counts))**2 ))**1/2
except ZeroDivisionError:
cnterr = (counts/np.mean(counts))*(((meanerr/np.mean(counts))**2 ))**1/2
RuntimeWarning: divide by zero encountered in divide
cnterr = (counts/np.mean(counts))*(((cnterr/counts)**2 + (meanerr/np.mean(counts))**2 ))**1/2
And also by np.where()
:
cnterr = np.where(counts != 0, ((counts/np.mean(counts))*(((cnterr/counts)**2 + (meanerr/np.mean(counts))**2 ))**1/2), 0)
Raise the same error.
回答1:
To sum values except divide by 0
,
sel = b != 0
c = np.sum(a[sel]/b[sel])
The arrays are float
, you may need to use
sel = np.bitwise_not(np.isclose(b, 0))
UPDATE
If a
and b
are not np.array
, write the follow code in the first.
a = np.array(a)
b = np.array(b)
回答2:
c = np.where(b != 0, a/b, 0).sum()
See: http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html
回答3:
This works, it puts a 0
in the list where there is a divide by zero:
c = np.sum([x/y if y else 0 for x,y in zip(a,b)])
Or, a variation on @mskimm's answer. Note, you first need to convert your input lists to numpy arrays:
a=np.array(a)
b=np.array(b)
c=np.sum(a[b!=0]/b[b!=0])
回答4:
This should work.
c = []
for i, j in enumerate(a):
if b[i] != 0:
c += [j/b[i]]
else:
c += [0]
c = sum(c)
回答5:
This is also simple:
c = 0 if 0 in b else sum(a/b)
来源:https://stackoverflow.com/questions/23129407/return-zero-value-if-division-by-zero-encountered