Using NumPy to Convert Array Elements to Float Type

02 Sep, 2020
There are often times when it is necessary for us to 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.
Method 1 : 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 convertedArray. 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.
# Process utilizing astype() function  # Import NumPy Libraryimport numpy as np  # Initialize our Array with Strings# The String Type is denoted by the quotes ""initialArray = ["1.1", "2.2", "3.3", "4.4"]  # Convert initial Array to NumPy Array# Use the array() functionsampleArray = np.array(initialArray)  # Print our Initial Arrayprint("Our initial array: ", str(initialArray))print("Original type: " + str(type(initialArray[0])))  # Actual Conversion of Array# Note usage of astype() function# np.float can be changed to represent differing typesconvertedArray = sampleArray.astype(np.float)  # Print our final result# Note that usage of str() is due to Python conventionsprint("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'>

Method 2 : Here, we will utilize the asarray() function that is offered by NumPy.
# Process utilizing asarray() function  # Import NumPy Libraryimport numpy as np  # Initialize our array# Note, once again, that this is of type String# Non-NumPy arrays can be usedinitialArray = np.array(["1.1", "2.2", "3.3", "4.4"])  # Print our initial arrayprint("Our Initial Array: ", str(initialArray))print("Original type: " + str(type(initialArray[0])))  # Actual conversion of array# Note that we utilize np.float64 as the finalize data typefinalArray = np.asarray(initialArray, dtype = np.float64,                         order ='C')  # Print our converted arrayprint("Our Final Array: ", str(finalArray))print("Final type: " + str(type(finalArray[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'>

Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python