Open In App

Using NumPy to Convert Array Elements to Float Type

Last Updated : 21 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

There are often when we must convert an array in Python to a differing type. One of these times would be when given an array and having to convert it to an array of float types. This is often useful when conducting data analysis and there are a variety of ways of doing this. Whilst iterating through the array and using Python‘s inbuilt float() casting function is perfectly valid, NumPy offers us some even more elegant ways to conduct the same procedure.

Array to Float Conversion using NumPy

There are various methods for using Numpy to convert Array elements to different DataType but in this, we will explore converting Numpy array elements To Float type:

  • Using astype() method
  • Convert NumPy Longdouble to Float using astype()
  • Specifying dtype Parameter
  • Handling In-Place Conversion
  • Using Universal Functions
  • Using Vectorization with NumPy

Convert NumPy Array to Float using astype() Method

Here, we can utilize the astype() function that is offered by NumPy. This function creates another copy of the initial array with the specified data type, float in this case, and we can then assign this copy to a specific identifier, which is converted Array. Note that the data type is specified in terms of NumPy, mainly because of the constraints of the NumPy astype() function, which will only take NumPy types as parameters.

Python3




# Process utilizing astype() function
import numpy as np
 
initialArray = ["1.1", "2.2", "3.3", "4.4"]
 
sampleArray = np.array(initialArray)
print("Our initial array: ", str(initialArray))
print("Original type: " + str(type(initialArray[0])))
 
# Note usage of astype() function
# np.float can be changed to represent differing types
convertedArray = sampleArray.astype(np.float)
 
print("Our final array: ", str(convertedArray))
print("Final type: " + str(type(convertedArray[0])))


Output :

Our initial array:  ['1.1', '2.2', '3.3', '4.4']
Original type: <class 'numpy.str_'>
Our final array: [1.1 2.2 3.3 4.4]
Final type: <class 'numpy.float64'>

Convert NumPy Longdouble to Float using astype()

In this example we convert numpy longdouble to float using astype(). In NumPy, converting a longdouble to float involves using the astype() method or creating a new array with the desired data type.

Python3




import numpy as np
 
# Create a NumPy array with longdouble data type
longdouble_array = np.array([3.141592653589793238], dtype=np.longdouble)
 
# Convert longdouble to float using astype() method
float_array = longdouble_array.astype(float)
 
# Alternatively, create a new array with float data type
float_array_new = np.array(longdouble_array, dtype=float)
 
# Print the original and converted arrays
print("Original longdouble array:")
print(longdouble_array)
print("\nConverted float array using astype():")
print(float_array)
print("\nConverted float array using new array creation:")
print(float_array_new)


Output:

Original longdouble array:
[3.14159265]

Converted float array using astype():
[3.14159265]

Converted float array using new array creation:
[3.14159265]

Convert an Array Element to a Float by Specifying dtype Parameter

We can also specify the data type during array creation using the dtype parameter. This method is particularly useful when creating a new array with a specific data type.

Python3




import numpy as np
 
# Example NumPy array (integer)
integer_array = np.array(["1.1", "2.2", "3.3", "4.4"])
 
# Convert to float specifying dtype
float_array = np.array(integer_array, dtype=float)
 
print("Original Array (Integer):", integer_array)
print("Converted Array (Float):", float_array)


Output:

Original Array (Integer): ['1.1' '2.2' '3.3' '4.4']
Converted Array (Float): [1.1 2.2 3.3 4.4]

 Change the Datatype of an Array in NumPy by Handling In-Place Conversion

In-place conversion involves directly modifying the existing array without creating a new one. In this example, we perform in-place conversion using the astype() method and update the integer_array to be of float type.

Python3




import numpy as np
 
# Example NumPy array (integer)
integer_array = np.array([100, 200, 300, 400, 500])
 
# In-place conversion to float
integer_array = integer_array.astype(float)
 
print("Converted Array (Float):", integer_array)


Output:

Converted Array (Float): [100. 200. 300. 400. 500.]

Convert an array of Strings to an Array of Floats in NumPy using Universal Functions

Universal functions, or ufuncs, are functions that operate element-wise on arrays. NumPy provides ufuncs for various operations, including data type conversion. The np.float64() ufunc is used to convert the array to the float data type.

Python3




import numpy as np
 
# Example NumPy array (integer)
integer_array = np.array([7, 8, 9, 10, 11])
 
# Use ufunc to convert to float
float_array = np.float64(integer_array)
 
print("Original Array (Integer):", integer_array)
print("Converted Array (Float):", float_array)


Output:

Original Array (Integer): [ 7  8  9 10 11]
Converted Array (Float): [ 7. 8. 9. 10. 11.]

Array converted to a Float type using Vectorization with NumPy

Vectorization involves applying a function to each element of an array, avoiding explicit loops. In this example, the np.vectorize() function is used to apply the float() function to each element of the integer_array, producing a float array.

Python3




import numpy as np
 
integer_array = np.array([15, 16, 17, 18, 19])
 
# Vectorized conversion to float
float_array = np.vectorize(float)(integer_array)
 
print("Original Array (Integer):", integer_array)
print("Converted Array (Float):", float_array)


Output:

Original Array (Integer): [15 16 17 18 19]
Converted Array (Float): [15. 16. 17. 18. 19.]

Convert Datatypes of Arrays using NumPy in Python by Casting During Array Creation

In NumPy, you can explicitly set the data type of an array during its creation using the dtype parameter.

Python3




import numpy as np
 
# Example 1: Casting during array creation
integer_array = np.array([1, 2, 3, 4, 5], dtype=np.float64)
float_array = np.array([1.1, 2.2, 3.3, 4.4, 5.5], dtype=np.int32)
 
print("Integer Array with Float64 Data Type:")
print(integer_array)
 
print("\nFloat Array with Int32 Data Type:")
print(float_array)


Output:

Integer Array with Float64 Data Type:
[1. 2. 3. 4. 5.]
Float Array with Int32 Data Type:
[1 2 3 4 5]



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads