首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python -将列表的字符串值转换为浮点值

Python -将列表的字符串值转换为浮点值
EN

Stack Overflow用户
提问于 2017-04-23 14:59:47
回答 1查看 574关注 0票数 2

我想存储列表的浮动值。这些值是从csv文件中提取的。

我所写的代码:

代码语言:javascript
复制
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))

我遇到的错误是:

代码语言:javascript
复制
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: '.'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-23 15:08:05

当你这样做时:

代码语言:javascript
复制
data1 = open('data.csv','r').read().split("\n")

data1是一个字符串列表

所以你就这么做:

代码语言:javascript
复制
x1 = [[float(n) for n in e] for e in data1 ]

您正在迭代字符串,然后迭代字符串的字符。因此,转换(某种程度上)适用于第一个浮点数的第一个数字,然后在.上进行转换(例如:"3.1416"3被转换为浮点数(以一种有趣的方式工作),但之后您会遇到.,幸运的是,它失败了)。

你只是忘了按照csv分隔符来分割你的线路。

我将使用csv模块将行拆分为行,然后执行以下操作:

代码语言:javascript
复制
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]
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43572702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档