w3resource

NumPy: Array converted to a float type


Convert Array to Float Type

Write a NumPy program to convert an array to a floating type.

Python NumPy: Array converted to a float 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’.


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:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.