Home »
Python »
Python Programs
How to convert an array of strings to an array of floats in NumPy?
Learn, how to convert an array of strings to an array of floats in NumPy?
By Pranit Sharma Last updated : October 08, 2023
NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.
The string is a group of characters, these characters may consist of all the lower case, upper case, and special characters present on the keyboard of a computer system. A string is a data type and the number of characters in a string is known as the length of the string.
Problem statement
Suppose get we are given a NumPy array containing string elements and we need to convert them into float elements.
Converting an array of strings to an array of floats in NumPy
For this purpose, we will use the astype() method inside which we will pass the np.float as an argument. The astype() method Cast a pandas object to a specified dtype.
Let us understand with the help of an example,
Python program to convert an array of strings to an array of floats in NumPy
# Import numpy
import numpy as np
# Creating a numpy array
arr = np.array(['1.1', '2.2', '3.3'])
# Display original array
print("Original Array:\n",arr,"\n")
# Converting type of arr from string to float
res = arr.astype(float)
# Display result
print("Converted array:\n",arr,"\n")
# Display arr data type
print("DataType:\n",arr.dtype)
Output
The output of the above program is:
Python NumPy Programs »