My Coding > Programming language > Python > Python libraries and packages > Python NumPy > How to divide NumPy array with zero divisor

How to divide NumPy array with zero divisor

A widespread problem in dividing one array of data by another array of data is a zero in divisor. It can happen due to many reasons, for example not very good, or missed data, very small, almost zero divisor data, or any other reasons.

import numpy as np

a = np.array([10.,20.,30.,40.])
b = np.array([2., 3., 0., 4.])
c = a/b
# [5.         6.66666667        inf]
#/tmp/ipykernel_786294/ RuntimeWarning: 
# divide by zero encountered in true_divide c = a/b

This problem can be handled in NumPy in two different ways.


When you divide something by zero, you will have infinity or undefined results, but infinity is a more physically correct value. By default, NumPy uses inf as a result of dividing by zero and throwing a warning to the output. If you are happy with these results, you can suppress the warning from the zero divisor by following the command:


Fixed results or limits

If you know that the results should be fixed, then you can use the NumPy divide function as follows:

c = np.divide(a,b,
#[5.         6.66666667 1.        ]

In this code, we divide NumPy array a by b. With the results we will fill array out with is equal in our case one-filled array like a, and this division will be performed only for those elements, where respective divisor b value is not equal 0.0.

Or, otherwise, where the divisor b value is equal to 0.0, the division will not be performed and the respective array element will not be changed (it will be 1.0).

Or you can create an array for filling with zero by command out=np.zeroes_like(a)

Published: 2023-10-10 00:53:36
Updated: 2023-10-10 00:55:28

Last 10 artitles

9 popular artitles

© 2020 -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.