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。任何人都可以对这个问题提出任何建议吗?我会很感激任何帮助。
非常感谢您的回复。你能解释一下这个dtype吗?当我声明数组或当我添加值时,是否使用它? –
http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html 这也应该在你的课程或培训材料。 – Prune
谢谢。我只是自己学习,并尝试从小型项目开始。我抬头看了看文档,并将声明更改为:“depth = np.array(dtype = float32)” 我收到另一条错误消息:“NameError:name'float32'未定义。在使用之前我错过了什么? –