将float从两列文本文件读取到Python中的数组时出错

时间:2013-09-26 08:49:20

标签: python numpy matplotlib

我有一个文本文件,其中包含由选项卡分隔的2列,包含一些我想要读入数组的数据,并执行一些简单的操作,例如绘制数据。第二列中的数据是科学记数法,并且可以采用极小的值,例如从数量级10e-27 10e-50变化。例如,这是一个数据样本

0.00521135   -1.197189e-31
0.00529274   -7.0272737e-32
0.00530917   -6.0163467e-32
0.00532565   -4.9990405e-32
0.00534218   -3.9747722e-32
0.00535876   -2.9457271e-32
0.0053754    -1.9094542e-32
0.00539208   -8.6847519e-33
0.00540882    1.7851373e-33
0.00542561    1.2288483e-32
0.00544245    2.2850705e-32
0.00545934    3.3432858e-32
0.00547629    4.4084594e-32
0.00549329    5.4765499e-32
0.00551034    6.5491709e-32

以下是我的代码:

import numpy as np
import matplotlib.pyplot as plt
with open('data.dat', 'r') as f2:
lines = f2.readlines()
data = [line.split()for line in lines] 
data2 = np.asfarray(data)
x1 = data2[:,0]
y1 = data2[:,1]
plt.plot(x1, y1)
plt.show()

我已经使用此代码测试样本数据(.dat格式)文件,它似乎工作正常,但是当我在我的数据集上运行此代码时,它会给我以下错误。

Traceback (most recent call last):
File "read_txt_col.py", line 17, in <module>
data2 = np.asfarray(data)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages  /numpy/lib/type_check.py", line 103, in asfarray
return asarray(a,dtype=dtype)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/numeric.py", line 235, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.

有人可以帮忙!!

1 个答案:

答案 0 :(得分:8)

不要重新发明轮子!使用numpy.loadtxt

会更容易
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> data = np.loadtxt('data.dat')
>>> x1 = data[:,0]
>>> y1 = data[:,1]
>>> plt.plot(x1, y1)
>>> plt.show()

enter image description here