Python - 将列表的字符串值转换为浮点值
问题描述:
我想存储列表的浮点值。这些值是从csv文件中提取的。Python - 将列表的字符串值转换为浮点值
我写的代码:
import numpy as np
import csv
from sklearn import datasets, metrics
from sklearn.model_selection import train_test_split
from neupy import algorithms, environment
environment.reproducible()
data1 = open('data.csv','r').read().split("\n")
target1 = open('target.csv','r').read().split("\n")
x1 = [[float(n) for n in e] for e in data1 ]
y1 = [[float(s) for s in f] for f in target1 ]
x_train, x_test, y_train, y_test = train_test_split(x1,y1,train_size=0.7)
pnn = algorithms.PNN(std=10,verbose=False)
pnn.train(x_train, y_train)
y_predicted = pnn.predict(x_test)
print(metrics.accuracy_score(y_test, y_predicted))
我所遇到的错误是:
WARNING (theano.configdefaults): g++ not detected ! Theano will be
unable to execute optimized C-implementations (for both CPU and GPU)
and will default to Python implementations. Performance will be
severely degraded. To remove this warning, set Theano flags cxx to
an empty string.
Traceback (most recent call last):
File "C:\Users\pc\AppData\Local\Programs\Python\Python36-32\pnn-3.py", line 16, in <module>
x1 = [[float(n) for n in e] for e in data1 ]
File "C:\Users\pc\AppData\Local\Programs\Python\Python36-32\pnn-3.py", line 16, in <listcomp>
x1 = [[float(n) for n in e] for e in data1 ]
File "C:\Users\pc\AppData\Local\Programs\Python\Python36-32\pnn-3.py", line 16, in <listcomp>
x1 = [[float(n) for n in e] for e in data1 ]
ValueError: could not convert string to float: '.'
答
,当你这样做:
data1 = open('data.csv','r').read().split("\n")
data1
是列表字符串
,那么你这样做:
x1 = [[float(n) for n in e] for e in data1 ]
你遍历对字符串,然后在字符的字符串。因此,转换(种类)适用于第一个浮点数的第一个数字,然后在.
(例如:"3.1416"
:3
)上的扼流圈被转换为浮点数(有趣的工作方式),但后来遇到.
,幸运的是失败) 。
你只是忘了根据csv分隔符分割你的行。
我会用csv
模块到线到行分割为我做:
with open('data.csv','r') as f:
cr = csv.reader(f,delimiter=";") # change to whatever your delimiter is
x1 = [[float(n) for n in row] for row in cr]
+0
它比thanx –
欢迎*上。请阅读[我如何问一个好问题?](http://*.com/help/how-to-ask)和[如何创建最小,完整和可验证的示例](http:// *。 com/help/mcve),然后回来重新编写你的问题 –
我会说'e'已经是一个表示浮点数的字符串了,所以转换(种类)一直工作,直到它在点上扼杀。尝试'x1 = [float(n)for n in data1]' –
再次出现同样错误 –