为什么numpy.fromstring读取数字错误?

问题描述 投票:0回答:2

我正在编写使用numpy.fromstring从xml元素文本读取数组的代码。

它运行没有错误,但是读取的内容非常奇怪。

例如

import numpy as np

nr = 24
r_string = '''
0.0000    0.0100    0.0200    0.0300    0.0400    0.0500    0.0600    0.0700
0.0800    0.0900    0.1000    0.1100    0.1200    0.1300    0.1400    0.1500
0.1600    0.1700    0.1800    0.1900    0.2000    0.2100    0.2200    0.2300
'''

r = np.fromstring(r_string, count = nr)

print(r)

打印以下内容(垃圾)

[1.20737375e-153 1.48440234e-076 1.30354286e-076 6.96312257e-077
 6.01356142e-154 1.20737830e-153 1.82984908e-076 1.30354286e-076
 6.96312257e-077 3.22522589e-086 6.01347037e-154 6.03686893e-154
 1.39804459e-076 9.72377416e-072 3.24245662e-086 6.01347037e-154
 6.03686880e-154 1.39939399e-076 1.79371973e-052 1.91654811e-076
 8.54289848e-072 6.96312257e-077 6.01356142e-154 1.20738399e-153]

这里发生了什么?

在此感谢您的帮助。

python numpy
2个回答
0
投票

您需要声明sep=' '

>>> r = np.fromstring(r_string, count = nr, sep=' ')
>>> r
array([0.  , 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1 ,
       0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2 , 0.21,
       0.22, 0.23])

0
投票

您需要指定分隔符,例如:

np.fromstring(r_string, sep="\t")

输出:

array([0.  , 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1 ,
       0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, 0.18, 0.19, 0.2 , 0.21,
       0.22, 0.23])
© www.soinside.com 2019 - 2024. All rights reserved.