NumPy: numpy.asfarray() function
numpy.asfarray() function
The numpy.asfarray() function is used to convert an input array to a floating-point array.
The main application of numpy.asfarray() function is in scientific computing where it is necessary to convert the input array to a floating-point type before performing various mathematical operations on the array.
Syntax:
numpy.asfarray(a, dtype=<class 'numpy.float64'>)
Parameters:
Name | Description | Required / Optional |
---|---|---|
a | Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays. | Requireed |
dtype | Float type code to coerce input array a. If dtype is one of the 'int' dtypes, it is replaced with float64. | Optional |
Return value:
out : ndarray The input 'a' as a float ndarray.
Example: Converting an array to a float array using numpy.asfarray()
>>> import numpy as np
>>> np.asfarray([5, 7])
array([ 5., 7.])
In the above code, an array of integers [5, 7] is passed as an argument to the numpy.asfarray() function. The function returns a float array of the same shape as the input array, but with each element converted to float data type.
Pictorial Presentation:
Example: Converting an array to float using numpy.asfarray()
>>> import numpy as np
>>> np.asfarray([5, 7], dtype='float')
array([ 5., 7.])
>>> np.asfarray([5, 7], dtype='int8')
array([ 5., 7.])
- In the second line, the asfarray() function is used to convert an array containing integer values [5, 7] to a float array [5.0, 7.0].
- In the fourth line, the asfarray() function is used to convert the same array to an array with a data type of int8, but the function returns an array of float64.
Python - NumPy Code Editor:
Previous: asmatrix()
Next: asfortranarray()
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/numpy/manipulation/asfarray.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics