2015-09-23 173 views
0

我正在尝试使用python来绘制图表。以下是导致错误的代码的简化版本。matplotlib.pyplot.plot,ValueError:无法将字符串转换为浮点数:f

import numpy as np 
import matplotlib 
import matplotlib.pyplot as plt 
matplotlib.use("AGG") 

distance = np.array('f') 
depth = np.array('f')# make sure these two arrays store float type value 

with open('Line671.txt','r') as datafile: 
    for line in datafile: 
    word_count = 0 
    for word in line.split(): 
     word = float(word)#convert string type to float 
     if word_count == 0: 
      distance = np.append(distance, word) 
     elif word_count == 1: 
      depth = np.append(depth, word) 
     else: 
      print 'Error' 
     word_count += 1 

datafile.closed 


print depth 
print distance #outputs looks correct 
# original data is like this: -5.3458000e+00 
# output of the array is :['f' '-5.3458' '-5.3463' ..., '-5.4902' '-5.4912' '-5.4926'] 

plt.plot(depth, distance)# here comes the problem 

该错误消息说,在行plt.plot(深度距离):ValueError异常:无法将字符串转换为float:F
我不明白这一点,因为它似乎我转换的所有字符串值变成浮动类型。我试图在stackoverflow上搜索这个问题,但他们似乎都解决了问题,一旦他们将所有字符串值转换为float或int。任何人都可以对这个问题提出任何建议吗?我会很感激任何帮助。

回答

0

您将该值与类型混淆。如果您试图声明该类型,则需要使用“dtype =”。你实际上做的是将单个字符粘贴到数组中。

要回答一个问题之后,你行

word = float(word) 

可能工作得很好。但是,我们无法分辨,因为您没有对结果值做任何事情。你是否期待这改变变量“行”内的原始内容?通用变量不会以这种方式工作。

+0

非常感谢您的回复。你能解释一下这个dtype吗?当我声明数组或当我添加值时,是否使用它? –

+0

http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html 这也应该在你的课程或培训材料。 – Prune

+0

谢谢。我只是自己学习,并尝试从小型项目开始。我抬头看了看文档,并将声明更改为:“depth = np.array(dtype = float32)” 我收到另一条错误消息:“NameError:name'float32'未定义。在使用之前我错过了什么? –

相关问题