# Numpy Divide in Python

In this Python tutorial, we will learn how to divide elements in NumPy array Python with different approaches and examples.

There are many ways to divide in Python Numpy, which are shown below:

• Numpy Divide in Python
• using scalar value by an array
• replacing any occurrences of NaN with a default value
• where the denominator is not zero
• using vector
• using the numpy.matrix
• using the numpy.linalg.solve function

Table of Contents

## Python numpy divide() function

In this section, we will discuss how to divide element-wise in NumPy array Python.

To perform this particular task we are going to use the numpy.divide() function. In Python, this function is used to calculate the division between two numpy arrays and this method provides several parameters that allow the user to specify the algorithm.

We can also use the / operator for dividing each and every item of an array. For example, suppose you have two NumPy arrays that contain integer values and we want to divide each value of the first numpy array with the second array by using numpy.divide() function and / operator.

Syntax:

Let’s have a look at the Syntax and understand the working of numpy.divide() function

``````numpy.divide
(
x1,
x2,
/,
out=None,
*,
where=True,
casting='same_kind',
order='K',
dtype=None,
subok=True
)``````
• It consists of a few parameters
• x1: This parameter indicates the array with dividend values.
• x2: Input array values for calculating the division.
• Out: By default it takes none value and it indicates the result is stored and if it is not provided a none value then a fresh allocated array is returned.

Example:

Let’s take an example and check how to divide two arrays in NumPy Python

Source Code:

``````import numpy as np

new_val = np.array([12,24,36])
new_val2 = np.array([2,12,4])
result=np.divide(new_val,new_val2)
print("Division of two arrays:",result)``````

In the above code first, we imported the numpy library and then created two arrays in which the dividend array ‘new_val’ and the divisor array ‘new_val2’. After that, we declared a variable ‘result’ and assigned numpy.divide() function in it. Once you will print ‘result’ then the output will display the result of dividing elements.

Here is the Screenshot of the following given code

This is how to use the numpy divide() function in Python.

## Numpy Divide in Python

Numpy makes division easy by providing different methods or ways to solve complex division problems. Here we are going to discuss some ways to perform the division operation in Numpy.

### Method-1: Numpy divide in Python using element-wise

This method divides the corresponding elements of two arrays element-wise, which means that the first element of the first array is divided by the first element of the second array, the second element of the first array is divided by the second element of the second array, and so on.

``````# Import the numpy module
import numpy as np

# Create numpy arrays 'arr1' and 'arr2'
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([2, 2, 2, 2, 2])

# Perform element-wise division of 'arr1' by 'arr2' using np.divide()
result = np.divide(arr1, arr2)

# Print the resulting numpy array
print(result)``````

The above code demonstrates the use of the NumPy library to perform element-wise division of two arrays.

The Python NumPy np.divide() method is used to perform element-wise division of “arr1” by “arr2”. The resulting array “result” will have the same shape as the original arrays, and each element in “result” will be the result of dividing the corresponding elements in “arr1” and “arr2”.

``Output: [0.5 1.  1.5 2.  2.5]``

Another Example:

Here is another example:

In this program, we will learn how to divide element-wise in NumPy array Python by using the / operator.

In Python, the / operator is used to divide one numpy array by another array, and the division operator/pass array and constant as operands and store two numpy arrays within a third variable.

Syntax:

Here is the syntax of / arithmetic operator for a division of an array.

``arr3=arr1/arr2``

Example:

Let’s take an example and understand the working of / operator.

Source Code:

``````import numpy as np

new_arr = np.array([49,25,36])
new_arr2 = np.array([7,5,6])

new_output = new_arr/new_arr2
print(new_output)``````

Here is the implementation of the following given code

As you can see in the above screenshot the output displays the new_array.

### Method-2: Numpy divide in Python using scalar value by an array

This method divides a scalar value by each element of an array. This is useful when you need to divide a fixed value by each element of an array.

``````# Importing the numpy library as np
import numpy as np

# Creating a numpy array with values 12, 21, 13, 14, and 15
arr = np.array([12, 21, 13, 14, 15])

# Creating a scalar with value 2
scalar = 2

# Dividing the scalar by each element in the array using the np.divide() method
result = np.divide(scalar, arr)

# Printing the resulting array
print(result)``````

The above code makes use of the NumPy library to perform element-wise division between a scalar value and a one-dimensional NumPy array.

• First, a NumPy array arr is created with five integer values. Then a scalar value of 2 is assigned to the variable scalar.
• The np.divide() function is used to perform element-wise division between scalar and arr. In this case, each element of arr is divided by scalar.
• The resulting array, result, contains the division results as floating-point numbers. It has the same shape as the original array arr.
``Output: [0.16666667 0.0952381  0.15384615 0.14285714 0.13333333]``

Another example:

In this section, we will discuss how to divide a numpy array element with a scaler value in Python.

In this example, we will take an array named ‘new_val’ that performs the method of dividend and the scaler value is 2 which indicates the divisor. Now we have to pass array and scaler value as an argument in numpy.divide() function.

Source Code:

``````import numpy as np

new_val = np.arange(2,6).reshape(2,2)
result=np.divide(new_val, 2)
print(result)``````

Here is the execution of the following given code

As you can see in the above screenshot the output displays the new array.

### Method-3: Numpy divide in Python replacing any occurrences of NaN with a default value

This method is similar to method 1, but it replaces any occurrences of NaN (Not a Number) in the first array with a default value before performing the division.

This is useful when you have missing values in your data and you want to replace them with a default value before performing the division.

``````import numpy as np

# create an array of floats and one of integers
arr1 = np.array([11.0, 22.0, 33.0, 44.0, 55.0, np.nan])
arr2 = np.array([2, 2, 2, 2, 2, 2])

# set a default value for division by zero
default_value = 0

# perform element-wise division of arr1 by arr2, setting a default value
# for division by zero and ignoring NaN values in arr1
result = np.divide(arr1, arr2, out=np.zeros_like(arr1), where=~np.isnan(arr1),
casting='unsafe')

# print the result
print(result)
``````

The above code creates two NumPy arrays, arr1 and arr2, one with floats and one with integers. It then sets a default value of 0 to use for division by zero.

• Next, it uses the np.divide() function to perform element-wise division of arr1 by arr2. The resulting array is stored in the result variable.
• The out parameter of np.divide() specifies the output array, which is initialized as an array of zeros with the same shape as arr1.
• The where parameter is used to specify a boolean condition that determines which elements of arr1 to include in the operation. In this case, it excludes elements that are NaN (not a number).
• Finally, the casting parameter specifies how to handle casting of data types. Here, it is set to ‘unsafe’, which means to use the default casting rules.
``Output: [ 5.5 11.  16.5 22.  27.5  0. ]``

### Method-4: Numpy divide in Python where the denominator is not zero

This method is similar to method 1, but it checks if the denominator is zero before performing the division. If the denominator is zero, the corresponding element in the resulting array is set to zero.

``````# Importing the numpy module as np
import numpy as np

# Creating two numpy arrays
arr1 = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
arr2 = np.array([2.0, 2.0, 0.0, 2.0, 2.0])

# Dividing the two arrays using np.divide() method and setting the value to zero where denominator is zero
result = np.divide(arr1, arr2, out=np.zeros_like(arr1), where=arr2!=0)

# Printing the result
print(result)``````

The above code imports the NumPy library as np, and defines two NumPy arrays arr1 and arr2 of length 5, with floating point values.

• The code then uses the np.divide() function to divide each element in arr1 by the corresponding element in arr2. A new NumPy array result is created to store the results.
• The out parameter is used to specify the output array, which is initialized as an array of zeros with the same shape and type as arr1. The where parameter is used to specify that division should only be performed where the corresponding element in arr2 is not zero.
• Finally, the resulting array `result
``Output: [0.5 1.  0.  2.  2.5]``

### Method-5: Numpy divide in Python using vector

``````import numpy as np

# Create a 2D NumPy array
new_val = np.array([[11,11,11],[25,25,25],[19,19,19]])

# Create a 1D NumPy array
new_vector = np.array([11,25,19])

# Divide the 2D array by the 1D array using broadcasting
# To perform division, the 1D array is converted into a column vector
# and then the division operation is applied to each row of the 2D array
new_result = new_val / new_vector[:,None]

# Print the result
print(new_result)
``````

The code starts by importing the NumPy library and then creates a 2-dimensional NumPy array called new_val with shape (3, 3). The values in new_val are integers, all set to the value 11, 25 or 19.

• Next, another NumPy array new_vector is created with shape (3,) and filled with the same integers as in new_val.
• Finally, a new NumPy array called new_result is created by dividing new_val by new_vecto`r` with broadcasting.
• In this case, the new_vector array is transformed into a 2-dimensional array with shape (3, 1) using [:, None] syntax. This makes it possible to divide each row of new_val by new_vector using element-wise division.
• The resulting new_result array has the same shape as new_val and new_vector and contains the element-wise division of each element.

Another example – Python numpy divide array by vector

In this Program, we will discuss how to divide a NumPy array by a vector in Python.

To perform this particular task we are going to use / operator for dividing the array by vector. First, we will create an array by using the np.array() function and assign integer values. After that declare a variable ‘new_vector’ and assign values in it.

Example:

``````import numpy as np

new_val = np.array([[11,11,11],[25,25,25],[19,19,19]])
new_vector = np.array([11,25,19])

new_result = new_val / new_vector[:,None]
print(new_result)``````

Here is the screenshot of the following given code

### Method-6: Numpy divide in Python using the numpy.matrix

This method involves creating a matrix from the vector using the `numpy.matrix()` function and then using matrix division to perform the element-wise division.

Although this method may be less efficient than the previous method, it can be useful for operations involving matrix multiplication, as NumPy matrix multiplication rules differ from those of arrays.

``````import numpy as np

# create a 1x2 array
arr = np.array([[2, 2]])

# create a 1x2 vector
vec = np.array([2, 2])

# create a matrix from the vector with dimensions 2x1
vec_matrix = np.matrix(vec)

# transpose the matrix to get a 1x2 matrix
vec_matrix_transpose = vec_matrix.T

# perform element-wise division of arr by vec_matrix_transpose
result = arr / vec_matrix_transpose

# print the result
print(result)
``````

The above code is performing an element-wise division of a 2D NumPy array arr by a 1D NumPy array vec.

• First, the 1D array vec is converted into a column vector using the np.matrix function, and then it is transposed using the T attribute to create a 2D column matrix vec_matrix.
• Then, the division operation is performed using the ‘/’ operator between the 2D array arr and the column matrix vec_matrix. This results in the division of each element in arr with the corresponding element in vec.
• Finally, the result is stored in the variable result and printed using the print function.
``````Output: [[1. 1.]
[1. 1.]]``````

### Method-7: Numpy divide in Python using the numpy.linalg.solve function

This method involves solving the equation Ax = B where A is the diagonal matrix represented by the vector, x is the unknown, and B is the array to be divided.

``````# Import the numpy library as np
import numpy as np

# Create a 3x2 array
arr = np.array([[1, 2],
[3, 4],
[5, 6]])

# Create a 1D array with two elements
vec = np.array([2, 2])

# Create a diagonal matrix with the elements of vec as diagonal elements
diag_mat = np.diag(vec)

# Solve the equation Ax = B for x using linalg.solve,
# where A is the transpose of the input array arr and B is the diagonal matrix diag_mat
res = np.linalg.solve(diag_mat, arr.T)

# Print the result
print(res)``````

The code above creates a 3×2 array and a 1D array with two elements using the NumPy library.

• Then, it creates a diagonal matrix with the elements of the 1D array as diagonal elements using the np.diag() function.
• The np.linalg.solve() function is then used to solve the equation Ax = B for x, where A is the transpose of the input array arr and B is the diagonal matrix diag_mat. The resulting matrix is printed to the console.
``````Output: [[0.5 1.5 2.5]
[1.  2.  3. ]]``````

You may also like to read the following related tutorials.

In this Python tutorial, we have learned how to divide elements in NumPy array Python.