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