Python|将字符串数组转换为浮点数组的方法
有时在竞争激烈的编码环境中,我们得到一些其他数据类型的输入,我们需要将它们转换为其他形式。这个问题与我们有一个字符串形式的输入,我们需要将其转换为浮点数相同。
让我们讨论几种将字符串数组转换为浮点数组的方法。
方法#1:使用 astype
Python3
# 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))
# converting to array of floats
# using np.astype
res = ini_array.astype(np.float)
# printing final result
print ("final array", str(res))
Python3
# 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))
# converting 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))
Python3
# 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))
# converting 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))
输出:
initial array ['1.1' '1.5' '2.7' '8.9']
final array [ 1.1 1.5 2.7 8.9]
方法 #2:使用 np.fromstring
Python3
# 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))
# converting 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))
输出:
initial array ['1.1' '1.5' '2.7' '8.9']
final array [ 1.1 1.5 2.7 8.9]
方法 #3:使用 np.asarray() 和类型
Python3
# 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))
# converting 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))
输出:
initial array ['1.1' '1.5' '2.7' '8.9']
final array [ 1.1 1.5 2.7 8.9]