This below should work and convert all NANs to 0

d[np.isnan(d)] = 0

If you want it all on one line, consider

d = np.nan_to_num(a1/a2)

Which will convert all NANs to 0, see here: http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.nan_to_num.html

Note: When dividing by 0, you should follow @imp9's solution below to avoid unnecessary warnings or errors.

Answer from Geotob on Stack Overflow
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.divide.html
numpy.divide — NumPy v2.4 Manual
Set whether to raise or warn on overflow, underflow and division by zero. Notes · Equivalent to x1 / x2 in terms of array-broadcasting. The true_divide(x1, x2) function is an alias for divide(x1, x2). Examples · Try it in your browser! >>> import numpy as np >>> np.divide(2.0, 4.0) 0.5 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.divide(x1, x2) array([[nan, 1.
Discussions

Dividing nan by 0
Firstly, NaN is called 'not a number' but it's a convention used in the floating point standard as an undefined value. That means it's still numeric and still a floating point value. Same like you can say that None is not a value but it still is an object, just like undefined in js. Secondly, NaN does prevail, in the context of numpy: In [5]: array1 = numpy.array([numpy.nan]) In [6]: array2 = numpy.array([0]) In [7]: array1/array2 Out[7]: array([nan]) It's just that in the 'regular' Python context, division by 0 triggers a ZeroDivisionError, basically because it doesn't have a NaN so instead it explicitly fails and leaves the resolution to the user (detecting a 0 denominator, switching to a library offering NaN, etc). More on reddit.com
🌐 r/learnpython
3
4
December 19, 2018
BUG (Possible): masked array divide by zero array seems to screen out nan and inf
Under certain circumstances dividing a masked array by regular array with zeros seems to unexpactantly screen out nan and inf answers. Reproducing code example: import numpy as np from numpy import ma # Make masked and regular array x = ... More on github.com
🌐 github.com
1
April 8, 2021
python - How to return 0 with divide by zero - Stack Overflow
Unless I'm missing something, it doesn't seem numpy.seterr() can return values upon errors. Does anyone have any other suggestions on how I could get the best out of numpy while setting my own divide by zero error handling? More on stackoverflow.com
🌐 stackoverflow.com
python - convert nan value to zero - Stack Overflow
My question is, is there a quick ... the 2D numpy array so that I have no problems with sorting and other things I am trying to do. ... The function isnan produces a bool array indicating where the NaN values are. A boolean array can by used to index an array of the same shape. Think of it like a mask. ... Sign up to request clarification or add additional context in comments. ... I just did this and have array([0.00000000e+00, 8.12981267e-07, 0.00000000e+00]) so now if I divide 1/array I ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
NumPy
numpy.org › devdocs › user › misc.html
Miscellaneous — NumPy v2.4.dev0 Manual
>>> x[3] = np.nan >>> x.sum() nan >>> np.nansum(x) 42.0 · The default is to 'warn' for invalid, divide, and overflow and 'ignore' for underflow. But this can be changed, and it can be set individually for different kinds of exceptions. The different behaviors are: ‘ignore’ : Take no action when the exception occurs. ‘warn’ : Print a RuntimeWarning (via the Python warnings module). ... Note that integer divide-by-zero is handled by the same machinery.
🌐
SciPy
docs.scipy.org › doc › numpy-1.14.0 › reference › generated › numpy.divide.html
numpy.divide — NumPy v1.14 Manual
January 8, 2018 - Equivalent to x1 / x2 in terms of array-broadcasting. Behavior on division by zero can be changed using seterr. In Python 2, when both x1 and x2 are of an integer type, divide will behave like floor_divide. In Python 3, it behaves like true_divide. ... >>> np.divide(2.0, 4.0) 0.5 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.divide(x1, x2) array([[ NaN...
🌐
Python Forum
python-forum.io › thread-37621.html
Division by zero and value of argument
I am new with python also new with this forum. I have searched this topic but didn't give me better solutions (may be my search skill is poor) import numpy as np from scipy import special def somb(x): return 0.5 if x == 0.0 else special.j1(x) /...
Find elsewhere
🌐
GitHub
github.com › numpy › numpy › issues › 18744
BUG (Possible): masked array divide by zero array seems to screen out nan and inf · Issue #18744 · numpy/numpy
April 8, 2021 - d = np.zeros((4, 2)) d[:,0] = somefunc3(xm, y) d Out[77]: array([[0., 0.], [1., 0.], [0., 0.], [1., 0.]]) Now it silently converted the masked array back to a regular array and put in 1 or 0 when it should be nan or inf. Note that when I ran this on my machine I got a divide by zero warning only one time, but all other times I ran it I did not (I have no idea why).
Author   jpkrooney
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.divide.html
numpy.divide — NumPy v2.5.dev0 Manual
Set whether to raise or warn on overflow, underflow and division by zero. Notes · Equivalent to x1 / x2 in terms of array-broadcasting. The true_divide(x1, x2) function is an alias for divide(x1, x2). Examples · Try it in your browser! >>> import numpy as np >>> np.divide(2.0, 4.0) 0.5 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.divide(x1, x2) array([[nan, 1.
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.divide.html
numpy.divide — NumPy v2.2 Manual
Set whether to raise or warn on overflow, underflow and division by zero. Notes · Equivalent to x1 / x2 in terms of array-broadcasting. The true_divide(x1, x2) function is an alias for divide(x1, x2). Examples · >>> import numpy as np >>> np.divide(2.0, 4.0) 0.5 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.divide(x1, x2) array([[nan, 1.
🌐
Readthedocs
stable-baselines.readthedocs.io › en › master › guide › checking_nan.html
Dealing with NaNs and infs — Stable Baselines 2.10.3a0 documentation
Invalid operation (\(\sqrt{-1}\), \(\inf \times 1\), \(\text{NaN}\ \mathrm{mod}\ 1\), …) return NaN ... Inexact (not representable exactly in base 2, eg: \(1/5\)) returns the rounded value (ex: assert (1/5) * 3 == 0.6000000000000001) And of these, only Division by zero will signal an exception, the rest will propagate invalid values quietly. In python, dividing by zero will indeed raise the exception: ZeroDivisionError: float division by zero, but ignores the rest. The default in numpy, will warn: RuntimeWarning: invalid value encountered but will not halt the code.
🌐
SciPy
docs.scipy.org › doc › numpy-1.9.3 › reference › generated › numpy.divide.html
numpy.divide — NumPy v1.9 Manual
October 18, 2015 - Equivalent to x1 / x2 in terms of array-broadcasting. Behavior on division by zero can be changed using seterr. When both x1 and x2 are of an integer type, divide will return integers and throw away the fractional part. Moreover, division by zero always yields zero in integer arithmetic. Examples · >>> np.divide(2.0, 4.0) 0.5 >>> x1 = np.arange(9.0).reshape((3, 3)) >>> x2 = np.arange(3.0) >>> np.divide(x1, x2) array([[ NaN, 1.
🌐
Medium
medium.com › @whyamit404 › numpy-divide-with-examples-c6594e2d0c3f
NumPy divide() (With Examples). If you think you need to spend $2,000… | by whyamit404 | Medium
February 8, 2025 - This might surprise you: NumPy doesn’t throw an error when dividing by zero. Instead, it returns inf (infinity) if the numerator isn’t zero, or nan (not a number) if both the numerator and denominator are zero.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-numpy-replace-nan-with-zero-and-fill-positive-infinity-for-complex-input-values
Python NumPy - Replace NaN with zero and fill positive infinity for complex input values - GeeksforGeeks
July 23, 2025 - In this article, we will see how to replace NaN with zero and fill positive infinity for complex input values in Python. Numpy package provides us with the numpy.nan_to_num() method to replace NaN with zero and fill positive infinity for complex ...
🌐
IncludeHelp
includehelp.com › python › numpy-how-to-return-0-with-divide-by-zero.aspx
Python - NumPy: How to return 0 with divide by zero?
# Import numpy import numpy as np # Creating numpy arrays arr1 = np.array([-3, 0, 4, 2, 3], dtype=float) arr2 = np.array([ 0, 0, 0, 6, 7], dtype=float) # Display original arrays print("Original Array 1:\n",arr1,"\n") print("Original Array 2:\n",arr2,"\n") # Defining an expression # for division of arrays res = np.divide(arr1, arr2, out=np.zeros_like(arr1), where=arr2!=0) # Display result print("Result:\n",res)