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:
# Importing the NumPy library with an alias 'np'
import numpy as np
# Defining a Python list 'a' containing integers
a = [1, 2, 3, 4]
# Printing the original array 'a'
print("Original array")
print(a)
# Converting the array 'a' to a NumPy array of type float using asfarray()
x = np.asfarray(a)
# Printing the array 'x' after converting to a float type
print("Array converted to a float type:")
print(x)
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’.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics