2015-09-23 171 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'未定義。在使用之前我錯過了什麼? –

相關問題