Using NumPy to Convert Array Elements to Float Type
Converting array elements to float type in Python means transforming each item in an array into a floating-point number. For example, an array like ["1.1", "2.2", "3.3"] contains string representations of numbers, which need to be converted to floats for mathematical operations. Let's explore different methods to do this efficiently.
Using astype(float)
astype() method creates a new array with a specified data type. It does not modify the original array but instead returns a copy with the new type.
import numpy as np
a = np.array(["1.1", "2.2", "3.3"])
res = a.astype(float)
print(res)
Output
[1.1 2.2 3.3]
Explanation: Here, a string array a is converted to a float array res using astype(float), creating a new array without modifying the original.
Using dtype=float
NumPy allows you to define the type of elements directly during the creation of the array using the dtype parameter. This ensures all elements are stored as floats from the beginning.
import numpy as np
a = np.array(["1.1", "2.2", "3.3"], dtype=float)
print(a)
Output
[1.1 2.2 3.3]
Explanation: Here, a string list is directly converted to a NumPy float array a by specifying dtype=float during array creation, eliminating the need for separate type conversion.
Using np.float64()
np.float64() is a NumPy universal function (ufunc) that converts the elements of an array into 64-bit floating-point numbers. It is highly optimized and suited for numeric data.
import numpy as np
a = np.array([1, 2, 3])
res = np.float64(a)
print(res)
Output
[1. 2. 3.]
Explanation: Here, an integer array a is converted to a float array res using np.float64(), which casts the elements to 64-bit floating-point numbers efficiently.
In-Place Reassignment using astype()
This approach reuses the astype() method like before, but here you overwrite the original array with the converted one. It’s a form of in-place reassignment, not true in-place conversion which NumPy doesn’t support due to fixed data types .
import numpy as np
a = np.array([100, 200, 300])
a = a.astype(float)
print(a)
Output
[100. 200. 300.]
Explanation: Here, a is converted to float using astype(float) and reassigned to itself, updating the array without keeping the original.
Using np.vectorize(float)
np.vectorize() turns a regular Python function like float() into a NumPy-style function that can operate element-wise over arrays. Though not as fast as true vectorized operations, it's flexible.
import numpy as np
a = np.array(["15", "16", "17"])
res = np.vectorize(float)(a)
print(res)
Output
[15. 16. 17.]
Explanation: Here, np.vectorize(float) applies float() to each element of a, converting the string array to float element-wise.
Related Articles