loadtxt python3中的矩阵错误

时间:2014-03-19 11:59:38

标签: python-3.x numpy

在python中,我试图从文件加载2列矩阵。 我可以手动输入:

xdata = np.array([0.1639534, 0.2411005, 0.3130353, 0.3788510,  0.4381247, 0.5373147, 0.6135673, 0.6716365, 0.7506711,  0.8000908, 0.9000000])
ydata =np.array ([7.1257999E-04,9.6610998E-04,1.1894000E-03,1.3777000E-03,1.5285000E-03,1.7297000E-03,1.8226000E-03,1.8422999E-03,1.7741000E-03,1.6574000E-03,1.1877000E-03])

但是我希望它从文件中加载:

$ cat fit
0.16395341   0.71258E-03
0.24110050   0.96611E-03
0.31303529   0.11894E-02
0.37885098   0.13777E-02
0.43812473   0.15285E-02
0.53731472   0.17297E-02
0.61356731   0.18226E-02
0.67163649   0.18423E-02
0.75067115   0.17741E-02
0.80009080   0.16574E-02
0.90000000   0.11877E-02

来自thisthis, 我试过了

xdata, ydata =np.loadtxt(fit,delimiter=' ')

只知道:

$ python least.py 
Traceback (most recent call last):
  File "least.py", line 5, in <module>
    xdata, ydata =np.loadtxt(fit,delimiter=' ')
NameError: name 'fit' is not defined

这里出了什么问题?有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

您没有名为fit的变量。文件名是字符串'fit'。您还需要参数unpack=True来创建转换为解包的数组:

>>> xdata, ydata = np.loadtxt('fit', unpack=True)

>>> xdata
array([ 0.16395341,  0.2411005 ,  0.31303529,  0.37885098,  0.43812473,
        0.53731472,  0.61356731,  0.67163649,  0.75067115,  0.8000908 ,
        0.9       ])

>>> ydata
array([ 0.00071258,  0.00096611,  0.0011894 ,  0.0013777 ,  0.0015285 ,
        0.0017297 ,  0.0018226 ,  0.0018423 ,  0.0017741 ,  0.0016574 ,
        0.0011877 ])