What's the best way to handle zero denominators when dividing pandas DataFrame columns by each other in Python? for example:
df = pandas.DataFrame({"a": [1, 2, 0, 1, 5], "b": [0, 10, 20, 30, 50]})
df.a / df.b # yields error
I'd like the ratios where the denominator is zero to be registered as NA (numpy.nan
). How can this be done efficiently in pandas?
Casting to float64
does not work at level of columns:
In [29]: df
Out[29]:
a b
0 1 0
1 2 10
2 0 20
3 1 30
4 5 50
In [30]: df["a"].astype("float64") / df["b"].astype("float64")
...
FloatingPointError: divide by zero encountered in divide
How can I do it just for particular columns and not entire df?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…