NumPy: Array converted to a float type
Convert Array to Float Type
Write a NumPy program to convert an array to a floating type.
Sample Solution:
Python Code:
Sample Output:
Original array [1, 2, 3, 4] Array converted to a float type: [ 1. 2. 3. 4.]
Explanation:
In the above code -
a = [1, 2, 3, 4]: Defines a list a containing the integers 1, 2, 3, and 4.
x = np.asfarray(a): The np.asfarray() function converts the given list ‘a’ into a one-dimensional NumPy array with a floating-point data type (by default, it uses float64). In this case, the list ‘a’ contains integers, so they will be converted to floating-point numbers in the resulting NumPy array ‘x’.
For more Practice: Solve these Related Problems:
- Convert an integer array to a floating-point array and perform division to showcase float behavior.
- Change the data type of an array using astype and verify the conversion through arithmetic operations.
- Transform a mixed-type numeric list into a float array and check that all elements are decimals.
- Implement a conversion function that takes an array and a target dtype, then confirm the new type with type().
Go to:
PREV : Reverse Array
NEXT : 2D Array (Border 1, Inside 0)
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.