Python - invalid literal for float()

Asked

Viewed 988 times

2

I have an array that looks like this

training_set = [['03/11/2017' '16,94']
 ['01/11/2017' '16,90']
 ['31/10/2017' '16,77']
 ...

However, I cannot manipulate the numbers because they are in the form of string. How do I clean the data and leave it like this

training_set = [['03/11/2017' 16,94]
 ['01/11/2017' 16,90]
 ['31/10/2017' 16,77]

1 answer

2

The problem is in the format of its value, such as string. You are using the comma as decimal separator, but Python uses the dot. That is, to convert to float, your string should be something like '16.94'.

You can, before converting to float, try replacing the comma with the dot:

float('16,94'.replace(',', '.'))
  • 1

    This is the "quick and easy" way. It is good for those who are learning, etc - for a system that is going to be internationalized, the correct is to use locales - it is detailed in the answer to this question: https://answall.com/questions/221876/como-usar-v%C3%Guladra-in-python-time-in-stitch/222098#222098

  • This method using replace apparently does not work for arrays, running only for loose numbers. I received error ('numpy.ndarray' Object has in attribute 'replace'')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.