2014-03-19 28 views
0

在python中,我想從文件中載入一個2列矩陣。 我可以手動輸入此爲:在python3錯誤中載入一個矩陣

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

您沒有名爲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 ])