Python - 将字符串数组转换为浮点数组的方法
pythonserver side programmingprogramming更新于 2025/9/17 6:04:17
Python 中的字符串文字用单引号或双引号括起来。将字符串分配给变量的方法是使用变量名后跟等号和字符串。您可以使用三个引号将多行字符串分配给变量。
示例
# 使用 astype 将字符串数组转换为浮点数组
import numpy as np
# 初始化数组
ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
# 打印初始数组
print ("初始数组", str(ini_array))
# 转换为浮点数组
# 使用 np.astype
res = ini_array.astype(np.float)
# 打印最终结果
print ("最终数组", str(res))
# 使用 fromstring 将字符串数组转换为浮点数组
将 numpy 导入为 np
# 初始化数组
ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
# 打印初始数组
print ("初始数组", str(ini_array))
# 转换为浮点数组
# 使用 np.fromstring
ini_array = ', '.join(ini_array)
ini_array = np.fromstring(ini_array, dtype = np.float, sep =', ' )
# 打印最终结果
print ("最终数组", str(ini_array))
# 使用 asarray 将字符串数组转换为浮点数组
import numpy as np
# 初始化数组
ini_array = np.array(["1.1", "1.5", "2.7", "8.9"])
# 打印初始数组
print ("初始数组", str(ini_array))
# 转换为浮点数组
# 使用 np.asarray
final_array = b = np.asarray(ini_array,
dtype = np.float64, order ='C')
# 打印最终结果
print ("最终数组", str(final_array))
输出
(&39;initial array&39;, "['1.1' '1.5' '2.7' '8.9']")
('最终数组','[ 1.1 1.5 2.7 8.9]')
('初始数组',"['1.1' '1.5' '2.7' '8.9']")
('最终数组','[ 1.1 1.5 2.7 8.9]')
('初始数组',"['1.1' '1.5' '2.7' '8.9']")
('final array', '[ 1.1 1.5 2.7 8.9]')
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

