loadtxt ValueError:无法将字符串转换为浮点型

时间:2019-11-23 20:18:18

标签: python arrays python-3.x database text

我已经阅读了其他类似问题的问题,但是似乎没有答案可以解决我的问题。

我有一个.dat文件,看起来像:

Some text about what the file is
    A         B         C       D        E
  1.150e+00 1.820e+00 1.000e+00 1.467e+00 1.200e-00
  1.100e+00 1.780e+00 1.000e+00 1.667e+00 1.130e-00
  1.050e+00 1.750e+00 1.000e+00 1.129e+00 1.560e-00
  1.000e+00 1.722e+00 1.000e+00 1.148e+00 1.729e-00
  1.800e+00 1.709e+00 1.079e+00 1.947e+00 1.595e-00
  1.600e+00 1.700e+00 1.012e+00 1.310e+00 1.768e-00
  1.400e+00 1.695e+00 1.548e+00 1.628e+00 1.317e-00
  1.200e+00 1.704e+00 1.512e+00 1.492e+00 1.233e-00
  1.000e+00 1.723e+00 1.778e+00 1.586e+00 1.772e-00

我有一个.py代码来绘制E vs B

data = np.loadtxt('/Users/namesurname/folder/file.dat', delimiter = "  ", skiprows=2 )

with open(file.dat) as f:
    first_line = f.readline()

E, B = loadtxt(file.dat,unpack=True,skiprows=2)[4, 0:8], loadtxt(file.dat,unpack=True,skiprows=2)[1, 0:8]


但是我得到标题中列出的错误:

ValueError: could not convert string to float

任何想法和如何纠正这一点将不胜感激!

1 个答案:

答案 0 :(得分:1)

您的

ValueError: could not convert string to float

是由您问题中的第一个方块引起的。即

data = np.loadtxt('/Users/namesurname/folder/file.dat', delimiter = "  ", skiprows=2 )

我将忽略其他障碍。

尝试删除“ delimiter”。

这对我有用:

In : name = 'file.dat'
In : data = np.loadtxt(fname, skiprows=2 )

In : data
Out: 
array([[ 1.15 ,  1.82 ,  1.   ,  1.467,  1.2  ],
       [ 1.1  ,  1.78 ,  1.   ,  1.667,  1.13 ],
       [ 1.05 ,  1.75 ,  1.   ,  1.129,  1.56 ],
       [ 1.   ,  1.722,  1.   ,  1.148,  1.729],
       [ 1.8  ,  1.709,  1.079,  1.947,  1.595],
       [ 1.6  ,  1.7  ,  1.012,  1.31 ,  1.768],
       [ 1.4  ,  1.695,  1.548,  1.628,  1.317],
       [ 1.2  ,  1.704,  1.512,  1.492,  1.233],
       [ 1.   ,  1.723,  1.778,  1.586,  1.772]])