mauve
mauve

Reputation: 2763

Python is refusing to convert string to float

I'm reading in data from a .txt file that looks like this:

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  

When I read it in, I take the time and date and combine them for a strptime object and form a new dict. I also read the labels from the first line and use those as the keys for the new dict. I'm getting an error later in the script that says that to round the values, a float is required. When I flag the "float(a) for a" line, the variable explorer is telling me that the "type" of a is a string_ and its value is " 2.826471e+001" (quotes mine). I tried the ast eval option and it did not work.

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)]]

Upvotes: 0

Views: 445

Answers (2)

MinchinWeb
MinchinWeb

Reputation: 706

One option is to split the string, and then work out the math yourself.

i.e. 2.826471e+001 is equal to 2.826471 * 10^1

So use the code:

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

Upvotes: 1

jgritty
jgritty

Reputation: 11935

There is some other problem, that string is easily cast in both Python 2 and 3.

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

Upvotes: 0

Related Questions