2017-10-15 48 views
0

我已经pred_data.txt作为访问数数组中从该文件在Python

19.08541,17.41787,16.59118,16.03507,15.68560

20.01880,18.21,19.48975,19.32,19.29945

17.32453,17.434,15.4253,12.422,11.4311

f=open('pred_data.txt','r') 
for value in f: 
    exam=np.array(value) 
    pred=clf.predict(exam) 
    print(pred) 

当我运行它,我得到了

ValueError: could not convert string to float:'19.08541,17.41787,16.59118,16.03507,15.68560\n'

但是当我尝试这样的: example=np.array([19.08541,17.41787,16.59118,16.03507,15.68560]) pred=clf.predict(example)

我得到了预测的输出。如何从文件访问数据以获取输出?

回答

0

我没有测试这个,但没有帮助事先将行/值分割成数组? 我的意思是

for value in f: 
    exam=np.array(value.split(',')) 
    ... 

这样它会更容易,如果字符串转换列表为花车,而不是将全系列的花车作为字符串列表。

0

当您从文件中读取一行时,它会以str的形式出现。因此,在你的例子是:

for value in f: 
    np.array(value) 

是一样的:

np.array('19.08541,17.41787,16.59118,16.03507,15.68560\n') 

你需要得到一份有条去掉\n,并采用分体式打入实际的单位是:

values_strs = value.strip().split(',') 

但是,这将让你将一个strs列表。这是更好地施展那些使用float还有:

# This is a comprehension. It's a bit clearer and more obvious than 
# calling `map(float, value.strip().split(','))`, but they boil down 
# to a similar idea. 
values_flt = [float(v) for v in value.strip().split(',')] 

总之,你可以只简化为:

exam = np.array(float(v) for v in value.strip().split(',')) 
+0

当我用'考试= np.array(浮在value.strip V()。分裂( '')(V))'我喜欢这个<发生器对象在0x00000266DAF54410>在'打印(考试)' –

0

使用numpy的的loadtxt功能。

import numpy as np 
np_array = np.loadtxt('pre_data.txt', delimiter=',')