Using NumPy to Convert Array Elements to Float Type
Last Updated :
21 Dec, 2023
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]
Similar Reads
How to convert NumPy array to list ?
This article will guide you through the process of convert a NumPy array to a list in Python, employing various methods and providing detailed examples for better understanding. Convert NumPy Array to List There are various ways to convert NumPy Array to List here we are discussing some generally us
4 min read
How to get element-wise true division of an array using Numpy?
True Division in Python3 returns a floating result containing the remainder of the division. To get the true division of an array, NumPy library has a function numpy.true_divide(x1, x2). This function gives us the value of true division done on the arrays passed in the function. To get the element-w
2 min read
Convert Python List to numpy Arrays
NumPy arrays are more efficient than Python lists, especially for numerical operations on large datasets. NumPy provides two methods for converting a list into an array using numpy.array() and numpy.asarray(). In this article, we'll explore these two methods with examples for converting a list into
4 min read
How to Convert NumPy Matrix to Array
In NumPy, a matrix is essentially a two-dimensional NumPy array with a special subclass. In this article, we will see how we can convert NumPy Matrix to Array. Also, we will see different ways to convert NumPy Matrix to Array. Convert Python NumPy Matrix to an ArrayBelow are the ways by which we can
3 min read
How To Convert Numpy Array To Tensor?
The tf.convert_to_tensor() method from the TensorFlow library is used to convert a NumPy array into a Tensor. The distinction between a NumPy array and a tensor is that tensors, unlike NumPy arrays, are supported by accelerator memory such as the GPU, they have a faster processing speed. there are a
2 min read
How to Convert images to NumPy array?
Images are an easier way to represent the working model. In Machine Learning, Python uses the image data in the format of Height, Width, Channel format. i.e. Images are converted into Numpy Array in Height, Width, Channel format. Â In this article we will see How to Convert images to NumPy array? Mod
6 min read
How to convert a list and tuple into NumPy arrays?
In this article, let's discuss how to convert a list and tuple into arrays using NumPy. NumPy provides various methods to do the same using Python. Example: Input: [3, 4, 5, 6]Output: [3 4 5 6]Explanation: Python list is converted into NumPy ArrayInput: ([8, 4, 6], [1, 2, 3])Output: [[8 4 6] [1 2 3]
2 min read
How to Convert an image to NumPy array and saveit to CSV file using Python?
Let's see how to Convert an image to NumPy array and then save that array into CSV file in Python? First, we will learn about how to convert an image to a numpy ndarray. There are many methods to convert an image to ndarray, few of them are: Method 1: Using PIL and NumPy library. We will use PIL.Ima
4 min read
Ways to Convert a Python Dictionary to a NumPy Array
The task of converting a dictionary to a NumPy array involves transforming the dictionaryâs key-value pairs into a format suitable for NumPy. In Python, there are different ways to achieve this conversion, depending on the structure and organization of the resulting array.For example, consider a dic
3 min read
NumPy | Get the Powers of Array Values Element-Wise
To calculate the power of elements in an array we use the numpy.power() method of NumPy library. It raises the values of the first array to the powers in the second array. Example:Python3 import numpy as np # creating the array sample_array1 = np.arange(5) sample_array2 = np.arange(0, 10, 2) print("
3 min read