我將數據從.txt文件看起來像這樣寫着:Python是拒絕將字符串轉換爲浮動
Time Date Inlet Gas skin #1 SKIN #2 OUT GAS
°C °C °C °C
15:28:55 4/11/2015 2.826471e+001 2.217617e+001 2.408844e+001 2.771613e+001
當我看到它,我花時間和日期,並結合他們一個虛構的對象,並形成一個新的字典。我還從第一行讀取標籤,並將其用作新字典的關鍵字。稍後在腳本中出現一個錯誤,說明要舍入值,需要浮點數。當我將「float(a)」標記爲「行」時,變量資源管理器告訴我a的「類型」是string_,它的值是「2.826471e + 001」(引用我的)。我嘗試了ast eval選項,但沒有奏效。
dict_labels = [label for label in labels if not label == 'Time' and not label == 'Date' and not label == '']
current_array =np.array(current_array)
temp_dict = {}
temp_dict['Dates_Times'] = [datetime.strptime(i + ' ' + j, dateformat) for i,j in zip(current_array[:][:,labels.index('Date')], current_array[:][:,labels.index('Time')])]
for label in dict_labels:
temp_dict[label] = [float(a) for a in current_array[:][:,labels.index(label)]]
'>>>浮動( 「2.826471e + 001」) 28.26471'該輸入可以被解析只要找到。我認爲其他的東西在你的數據結構和算法中是不正確的。 – dsh
注意'float()'返回一個對象,並且列表理解創建一個新的列表對象。列表理解不會改變變量'current_array'引用的對象。也許在列表理解中創建浮點數後,您繼續使用原始數組中的字符串而不是新列表? – dsh