Python - Ways to convert array of strings to array of floats


String literals in python are surrounded by either single quotation marks, or double quotation marks. Assigning a string to a variable is done with the variable name followed by an equal sign and the string. You can assign a multiline string to a variable by using three quotes.

Example

 Live Demo

# array of strings to array of floats using astype
import numpy as np
# initialising array
ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
# printing initial array
print ("initial array", str(ini_array))
# conerting to array of floats
# using np.astype
res = ini_array.astype(np.float)
# printing final result
print ("final array", str(res))
# array of strings to array of floats using fromstring  
import numpy as np  
# initialising array
ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
# printing initial array
print ("initial array", str(ini_array))
# conerting to array of floats
# using np.fromstring
ini_array = ', '.join(ini_array)
ini_array = np.fromstring(ini_array, dtype = np.float, sep =', ' )
# printing final result
print ("final array", str(ini_array))
# converting array of strings to array of floats using asarray
import numpy as np
# initialising array
ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
# printing initial array
print ("initial array", str(ini_array))
# conerting to array of floats
# using np.asarray
final_array = b = np.asarray(ini_array,
   dtype = np.float64, order ='C')
# printing final result
print ("final array", str(final_array))

Output

('initial array', "['1.1' '1.5' '2.7' '8.9']")
('final array', '[ 1.1 1.5 2.7 8.9]')
('initial array', "['1.1' '1.5' '2.7' '8.9']")
('final array', '[ 1.1 1.5 2.7 8.9]')
('initial array', "['1.1' '1.5' '2.7' '8.9']")
('final array', '[ 1.1 1.5 2.7 8.9]')

Updated on: 06-Aug-2020

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements