簡體   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