  # Python | Ways to convert an array of strings to a floating point array

NumPy | Python Methods and Functions | String Variables

Method # 1: Using Astype

 ` # Python code to demonstrate conversion ` ` # array of strings to array of floats ` ` # using astype `   ` import ` ` numpy as np `   ` # initializing array ` ` ini_array ` ` = ` ` np.array ([` ` "1.1" ` `, ` `" 1.5 "` `, ` `" 2.7 " , "8.9" ]) ``    # printing the original array print ( "initial array" , str ( ini_array))   # connect to floating point array # using np.astype res = ini_array.astype (np. float )   # print the final result print ( " final array " , str (res)) `

Exit:

` 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`

` `

` # Python code to demonstrate conversion # array of strings to array of floats # using fromstring   import numpy as np   # initializing array ini_array = np.array ([ " 1.1 " , "1.5" , "2.7" , " 8.9 " ])    # print the original array print ( "initial array" , str (ini_array))   # connect to floating point array # using np.fromstring ini_array = `,` . join (ini_array) ini_array = np.fromstring (ini_array, dtype = np. float ,  sep = `,` )   # print the final result print ( "final array" , str ( ini_array)) `

` ` Exit:

` 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

 ` # Python code for demonstration ` ` # converting an array of strings to a floating point array ` ` # using asarray `   ` import numpy as np ``   # initializing array ini_array = np.array ( [ "1.1" , "1.5" , "2.7" , "8.9" ])   # print the original array print ( " initial array " , str (ini_array))   # connecting to a floating point array # using np.asarray final_array = b = np.asarray (ini_array,    dtype = np.float64, order = `C` )    # print the final result print ( "final array" , str (final_array)) `

Exit:

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