繁体   English   中英

matplotlib.pyplot.plot,ValueError:无法将字符串转换为float:f

[英]matplotlib.pyplot.plot, ValueError: could not convert string to float: f

我正在尝试使用python进行绘图。 下面是导致错误的我的代码的简化版本。

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(depth,distance):ValueError:无法将字符串转换为float:f
我不明白这一点,因为似乎我已将所有字符串值都转换为浮点类型。 我试图在stackoverflow上搜索此问题,但是一旦将所有字符串值都转换为float或int,它们似乎都可以解决问题。 有人可以对此问题提出任何建议吗? 如有任何帮助,我将不胜感激。

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

要回答以后的问题,您的电话

word = float(word)

可能工作得很好。 但是,我们不能说,因为您没有对结果值做任何事情。 您是否希望这会更改变量“行”内的原始行? 普通变量不能那样工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM