Python Numpy true_divide() Function – 7 Code Examples

Python Numpy true_divide() Function explained with code examples in jupyter notebook python

Let’s talk about the Python Numpy true_divide function. Also, let’s walk through some easy code examples to understand how the parameters of the true_divide() function work.

Python Numpy true_divide Function

This function works like the divide() function and executes the element-wise division between two arrays assigned to it as arguments. But what makes it special is that it handles exceptional cases i.e. taking care of complex numbers or what to do when the division by zero occurs and more.

Python Numpy true_divide() Function explained with code examples in jupyter notebook pythonpython numpy true divide function with code examples explanied practically

true divide function of python numpy explained code examples

 

Syntax

numpy.true_divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Parameters Explanation

  • The (x1 and x2) represent the arrays that will be used in the element-wise operation of division.
  • The (/) is called a ‘positional-only‘ marker and its role is to maintain a separation between the positional(x1, x2) and the keyword(remaining ones) arguments.
  • The ‘out’ parameter(optional) represents an array in which the result will be stored, or else a new array will be created for storing the output.
  • The (*) represents the start of arguments(keywords only) and it means that all the parameters to its right must be keyword arguments.
  • The (where) parameter(optional) can take an array of Booleans and it specifies which corresponding elements will be used in the division operation. If False, then no operation but if True then the operation will be executed on the specified items.
  • The optional parameter(casting) defines the rules and these are ‘no‘, ‘safe‘, or ‘equiv‘, ‘unsafe‘, ‘auto‘, ‘same_kind‘. Its default value is ‘same_kind‘.
  • The (order) optional parameter specifies the memory layout for the output array. The data it takes is ‘C'(C Style), ‘F'(Fortran Style), or ‘A'(Any).
  • The  (dtype) parameter(optional) specifies the data type of the output array, else the data type of the input array will be taken.
  • The (subok) parameter is also optional. If we pass True(default is True) to it, then the resulting array will have the same subclass as input arrays. Passing False to it will make the output array a base class array.

7 Examples of Implementing true_divide Function

Example 1: 1D Numpy Arrays

import numpy as np

array1 = np.array([2,5,8])
array2 = np.array([3,5,7])

resultA = np.true_divide(array1, array2)
print(resultA)

Output

[0.66666667 1.         1.14285714]

The 2 arrays’ corresponding items are divided and the result is stored inside a variable and displayed.

Example 2: Parameter ‘out’

arrayFirst = np.array([1, 2, 3])
arraySecond = np.array([2, 5, 6])

output_array = np.zeros(3)
result = np.true_divide(arrayFirst, arraySecond, out=output_array)
print(result)

Output

[0.5 0.4 0.5]

We used the zeros function to create an array of 3 items. We then passed it to the ‘out’ parameter and the result will store in this array. Make sure the shape of this array and the input array is the same.

Example 3: Parameter(where) Perform element-wise when the array is none zero

arr1 = np.array([1, 3, 35])
arr2 = np.array([2, 0, 5])

# execute element-wise division only where arr2 is non-zero
resul = np.true_divide(arr1, arr2, where=arr2 != 0)
print(resul)

Output

[0.5 1.5  7. ]

By using the ‘where’ parameter we specified that perform the division operation when the second array item is not zero.

Example 4: ‘casting’ Parameter of numpy.true_divide() Function

a1 = np.array([4,6,7], dtype=np.int32)
a2 = np.array([8,4,9], dtype=np.float64)

re = np.true_divide(ar1, ar2,casting='unsafe')
print(re)

Output

[0.5        1.5        0.77777778]

In this code, we specified the casting to be ‘unsafe’. The output can be seen that the items of the array are of float datatype.

Example 5: Parameter ‘order’ on 2D Array

array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([[2, 2], [2, 2]])

rArC = np.true_divide(array1, array2, order='C')
rArF = np.true_divide(array1, array2, order='F')

print(rArC) 
print(rArF)

Output

[[0.5 1. ]
 [1.5 2. ]]
[[0.5 1. ]
 [1.5 2. ]]

We specified ‘C’ and ‘F’ in the ‘order‘ parameter. We also printed the result. The first array shows the ‘C’ order array while the second one shows the ‘F’ order array.

Example 6: ‘dtype’ Parameter

ay1 = np.array([1, 8, 3])
ay2 = np.array([6, 3, 7])

resultArray = np.true_divide(ay1, ay2, dtype=np.float32)
print(resultArray)

Output

[0.16666667 2.6666667  0.42857143]

In this code, we explicitly specify the datatype of the output array to be float using the ‘dtype’ parameter. As a result, the resulting array items are of float data type even though we have integers in the input array.

Example 7: ‘subok’ Parameter of true_divide() Function

class MyArrayClass(np.ndarray):
    pass

ar1 = np.array([1, 2, 3], dtype=np.int32).view(MyArrayClass)
ar2 = np.array([2, 4, 5], dtype=np.float64).view(MyArrayClass)

# Perform element-wise division and keep the subclass in the output array
result = np.true_divide(ar1, ar2, subok=True)
print(result.__class__)

Output

<class '__main__.MyArrayClass'>

We can see that making the ‘subok’ parameter True will make the resulting array to have the same subclass as input arrays.

Conclusion

In conclusion, we have discussed the Python Numpy true_divide function with the help of Python code examples and with proper explanations.

Thank you for reading it.

Leave a Comment

Your email address will not be published. Required fields are marked *