NumPy: Array converted to a float type
NumPy: Array Object Exercise-7 with Solution
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:
Previous: Write a NumPy program to reverse an array (first element becomes last).
Next: Write a NumPy program to create a 2d array with 1 on the border and 0 inside.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://198.211.115.131/python-exercises/numpy/python-numpy-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics