python - Numpy np.fromstring() 没有按预期工作

标签 python numpy type-conversion

我已将一个数组作为字符串保存在文本文件中,希望在从文件读取时能够将其转换回数组:

str_arr = "[0.01 0.01 0.01 0.01 0.01 0.01]"
num_arr = np.fromstring(str_arr,dtype = np.float64 ,count = 6,sep = ' ')

whic 的结果是 num_array:

array([-1.00000000e+000,  6.94819184e-310,  6.94819184e-310,
        6.94818751e-310,  6.94818751e-310,  6.94818751e-310])

我期待一个 0.01 的数组

最佳答案

似乎np.fromstring不知道如何解释括号。您可以通过在调用函数之前剥离它们来解决这个问题:

a = "[0.01 0.01 0.01 0.01 0.01 0.01]"
num_arr = np.fromstring(a.strip('[]'), count = 6, sep = ' ')

array([0.01, 0.01, 0.01, 0.01, 0.01, 0.01])

另请注意,dtype 默认为 float,因此在这种情况下无需指定。

关于python - Numpy np.fromstring() 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54367816/

相关文章:

python - python中的对数插值

string - Perl $strings 到哈希表的转换

c# - 在 C# 中将 Excel 所有列读取为字符串

postgis - 更改 PostgreSQL 9.1 中列的数据类型

python - 如何在电子邮件中设置 Markdown 的默认样式

python - 写锁定文件有时找不到内容(打开 pickled pandas DataFrame 时)- EOFError : Ran out of input

python - 序列化大型 scipy 稀疏矩阵的最佳方法是什么?

python - 根据其他列表从列表中选择

python - 为什么 `conda update --all`没有全部更新?

python - 如何访问不同维度的多维 NumPy 数组的特定行?