2016-02-04 62 views
0

我將數據從.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)]] 
+1

'>>>浮動( 「2.826471e + 001」) 28.26471'該輸入可以被解析只要找到。我認爲其他的東西在你的數據結構和算法中是不正確的。 – dsh

+0

注意'float()'返回一個對象,並且列表理解創建一個新的列表對象。列表理解不會改變變量'current_array'引用的對象。也許在列表理解中創建浮點數後,您繼續使用原始數組中的字符串而不是新列表? – dsh

回答

1

一種選擇是分割字符串,然後制定出你自己算算。

2.826471e+001等於2.826471 * 10^1

所以使用的代碼:

temp_dict[label] = [float(a.split('e+')[0])*pow(10, int(a.split('e+')[1])) for a in current_array[:][:,labels.index(label)]]

+0

因爲有一個領先的空間,我最終使用拆分。事實證明,它後來掛在不同的變量上...我的日期時間對象。 – mauve

0

有一些其他的問題,該字符串很容易在Python中都投2和3

>>> float("2.826471e+001") 
28.26471 
+0

這是否值得成爲答案? – khajvah

+0

它回答了這個問題。也許這個問題很糟糕。 – jgritty