Python无法将字符串转换为float

时间:2016-03-24 07:55:34

标签: python numpy matplotlib

我的目标是使用来自不同文件的数据绘制3D散点图。

我试过这个:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = []
y = []
z = []

readfile = open('axeX.txt', 'r')
file = readfile.read().split('\n')
for plot in file:
    x = plot.split(',')
    x.append(x[0])

....      

注意:axeX.txt包含以下数据:

9.0745818614959717e-01
1.1413983106613159e+01
1.7582545280456543e+00

我收到了这个错误:

ValueError: could not convert string to float: 

3 个答案:

答案 0 :(得分:0)

使用float(x [0])将其从字符串转换为float

答案 1 :(得分:0)

您在每个循环中覆盖x

x = []
for plot in file:
    x = plot.split(',')
    x.append(float(x[0]))

因此,您将得到一个包含原始字符串的两个元素的列表以及文件中最后一行的转换后的浮点数:

['1.7582545280456543e+00', 1.7582545280456543]

无论你读了多少行。

尝试:

x = []
for plot in file:
    temp = plot.split(',')
    x.append(float(temp[0]))

如果您只有一列数字,如问题所示,您可以这样阅读x

with open('axeX.txt', 'r')  as fobj:
    x = [float(line) for line in fobj]

现在:

>>> x
[0.9074581861495972, 11.41398310661316, 1.7582545280456543]

答案 2 :(得分:0)

我认为您为了多种不同的目的而滥用x变量:

# here it's initialized - apparently you want to collect a list of numbers
x = []
for plot in file:
    # but here you assign the result of splitting a line of text from
    # your input file. I would use a different variable here
    x = plot.split(',')
    # and now you start appending to it again?
    x.append(x[0])

我会尝试:

x = []
for plot in file:
    fields = plot.split(',')
    x.append(float(fields[0]))