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

Sometimes in a competitive coding environment, we get input in some other datatypes and we need to convert them in other forms this problem is same as that we have an input in the form of string and we need to convert it into floats.
Let’s discuss a few ways to convert an array of strings to array of floats.

Method #1 : Using astype

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate converting 
# 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))

chevron_right


Output:



initial array ['1.1' '1.5' '2.7' '8.9']
final array [ 1.1  1.5  2.7  8.9]

 
Method #2: Using np.fromstring

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate converting 
# 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))

chevron_right


Output:

initial array ['1.1' '1.5' '2.7' '8.9']
final array [ 1.1  1.5  2.7  8.9]

 
Method #3: Using np.asarray() and type

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to demonstrate
# 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))

chevron_right


Output:

initial array ['1.1' '1.5' '2.7' '8.9']
final array [ 1.1  1.5  2.7  8.9]


My Personal Notes arrow_drop_up

Programming freaktech Enthusiast and have interest in learning new upcoming technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.