Divide arguments element-wise and display the result in a different type in Numpy



To divide arguments element-wise, use the numpy.divide() method in Python Numpy. The arr1 is considered Dividend array. The arr2 is considered Divisor array. The output is set "float" using the "dtype" parameter.

The out is a location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

NumPy offers comprehensive mathematical functions, random number generators, linear algebra routines, Fourier transforms, and more. It supports a wide range of hardware and computing platforms, and plays well with distributed, GPU, and sparse array libraries.

Steps

At first, import the required library −

import numpy as np

Create two 2D arrays −

arr1 = np.array([[14, 28, 56], [84, 56, 112]])
arr2 = np.array([[7, 14, 21], [28, 35, 56]])

Display the arrays −

print("Array 1...
", arr1) print("
Array 2...
", arr2)

Get the type of the arrays −

print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype)

Get the dimensions of the Arrays −

print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim)

Get the shape of the Arrays −

print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape)

To divide arguments element-wise, use the numpy.divide() method in Python Numpy. The arr1 is considered Dividend array. The arr2 is considered Divisor array. The output is set "float" using the "dtype" parameter:

print("
Result (divide element-wise)...
",np.divide(arr1, arr2, dtype = 'float'))

Example

import numpy as np

# Create two 2D arrays
arr1 = np.array([[14, 28, 56], [84, 56, 112]])
arr2 = np.array([[7, 14, 21], [28, 35, 56]])

# Display the arrays
print("Array 1...
", arr1) print("
Array 2...
", arr2) # Get the type of the arrays print("
Our Array 1 type...
", arr1.dtype) print("
Our Array 2 type...
", arr2.dtype) # Get the dimensions of the Arrays print("
Our Array 1 Dimensions...
",arr1.ndim) print("
Our Array 2 Dimensions...
",arr2.ndim) # Get the shape of the Arrays print("
Our Array 1 Shape...
",arr1.shape) print("
Our Array 2 Shape...
",arr2.shape) # To divide arguments element-wise, use the numpy.divide() method in Python Numpy # The arr1 is considered Dividend array # The arr2 is considered Divisor array # The output is set "float" using the "dtype" parameter print("
Result (divide element-wise)...
",np.divide(arr1, arr2, dtype = 'float'))

Output

Array 1...
[[ 14 28 56]
[ 84 56 112]]

Array 2...
[[ 7 14 21]
[28 35 56]]

Our Array 1 type...
int64

Our Array 2 type...
int64

Our Array 1 Dimensions...
2

Our Array 2 Dimensions...
2

Our Array 1 Shape...
(2, 3)

Our Array 2 Shape...
(2, 3)

Result (divide element-wise)...
[[2. 2. 2.66666667]
[3. 1.6 2. ]]

Advertisements