2017-07-26 380 views
0

我有一個帶有兩列(x,y)數據的文本文件。我想使用linregress來計算這個文件中的值的斜率和截距,因爲我認爲這是最簡單的。使用linregress計算斜率和截距

這份名單,這是閱讀,看起來像這樣

95 68 
94 67.99028594 
93 67.98057049 
92 67.97085365 
91 67.96113542 
90 67.9514158 
89 67.94169479 
88 67.93197239 
87 67.9222486 
86 67.91252341 
85 67.90279683 
84 67.89306886 
83 67.8833395 
82 67.87360874 
81 67.86387658 
80 67.85414303 
79 67.84440809 
78 67.83467174 
77 67.824934 
76 67.81519486 
75 67.80545432 
74 67.79571238 
73 67.78596905 
72 67.77622431 
71 67.76647817 
70 67.75673062 
69 67.74698168 
68 67.73723133 
67 67.72747958 
66 67.71772642 
65 67.70797186 
64 67.6982159 
63 67.68845852 
62 67.67869974 
61 67.66893956 
60 67.65917796 
59 67.64941496 
58 67.63965055 
57 67.62988473 
56 67.62011749 
55 67.61034885 
54 67.6005788 
53 67.59080733 
52 67.58103445 
51 67.57126015 
50 67.56148445 
49 67.55170732 
48 67.54192879 
47 67.53214883 
46 67.52236746 
45 67.51258468 
44 67.50280047 
43 67.49301485 
42 67.4832278 
41 67.47343934 
40 67.46364946 
39 67.45385816 
38 67.44406543 
37 67.43427129 
36 67.42447572 
35 67.41467872 
34 67.40488031 
33 67.39508047 
32 67.3852792 
31 67.37547651 
30 67.36567239 
29 67.35586684 
28 67.34605987 
27 67.33625147 
26 67.32644164 
25 67.31663038 
24 67.30681769 
23 67.29700357 
22 67.28718801 
21 67.27737103 
20 67.26755261 
19 67.25773276 
18 67.24791148 
17 67.23808876 
16 67.2282646 
15 67.21843901 
14 67.20861199 
13 67.19878352 
12 67.18895362 
11 67.17912228 
10 67.1692895 
9 67.15945528 
8 67.14961963 
7 67.13978253 
6 67.12994399 
5 67.120104 

我是新來的蟒蛇,並寫了,我曾希望做一些瑣碎的代碼:

import numpy as np 
import matplotlib.pyplot as plt 
from scipy import stats 
from scipy.stats import linregress 

fileNameIN_pres = '/Somepathhere/prescription.txt' 

with open(fileNameIN_pres) as f: 
    for l in f: 
     x, y = l.split() 
     X1 = np.array(x) 
     X2 = np.array(y) 
     print X1,X2 

    print linregress(X1,X2) 

當我打印X1和X2,我得到我想要的列,所以代碼做到了我想要的那一點。當我要求它打印linregress我得到一個錯誤:

File "/usr/local/lib/python2.7/site-packages/scipy/stats/_stats_mstats_common.py", line 87, in linregress 
    n = len(x) 
TypeError: len() of unsized object 
[Finished in 0.5s with exit code 1] 

任何建議如何解決這一問題將不勝感激。

回答

0

雖然我不知道確切的文件,這將是這樣的:

X = [] 
Y = [] 
with open(fileNameIN_pres) as f: 
    for l in f: 
     x, y = l.split() 
     X.append(x) 
     Y.append(y) 

X = np.asarray(X); 
Y = np.asarray(Y); 
model = linregress(X, Y) 
slope, intercept = model.slope, model.intercept 

您可以通過

predict = slope*new_x + intercept 
+0

謝謝預測從一個new_x你Y!我編輯了原稿以包含列表格式。我試着複製並粘貼你的答案,但是我得到一個新的錯誤:「TypeError:無法用靈活類型執行縮減」。這是什麼意思? –

+0

我必須指定明確這兩個值分別爲花車.... X.append(浮點(X)) Y.append(浮點(Y)) 似乎當我打印模式 LinregressResult工作(斜率= 0.0097765420267558675,截距= 67.072169262838045,右值= 0.99999855560881434,p值= 2.678067576140719e-248,stderr = 1.7613600886131683e-06) 再次感謝! –

相關問題