我有一个包含两列(x,y)数据的文本文件。我想使用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
我是python的新手,并编写了一些我希望会这样做的简单代码:
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 :(得分: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
你可以通过
从new_x预测你的Y.predict = slope*new_x + intercept