Converting negative number in string to float (Python)?

Cronos picture Cronos · Jan 30, 2018 · Viewed 7.6k times · Source

Ok. I give up.

I have a DataFrame with a column ("Amount") of large numbers:

Amount
-1 000 000,00
 4 848 903,00
-2 949 234,00
13 038 023,00
 7 985 232,00
 ....

I want to convert these to numbers that I can calculate with.

Let's investigate:

>type(b["Amount"][0])
str

Ok, it's a string.

>float("-1 000 000,00".replace(' ', '').replace(',','.'))
-1000000.00

Ok, works great!

To make a lambda thingy (to process all elements in column), I need it in a function:

def make_float(num):
    num = num.replace(' ','').replace(',','.')
    return float(num)


>make_float(b["Amount"][0])
ValueError: could not convert string to float: −1 000 000.00

What?!

>b["Amount"][0].replace(' ','').replace(',','.')
Out[258]:
'\xe2\x88\x921\xc2\xa0000\xc2\xa0000.00'

Oh no!! Unicode hell! I give up.

Does Python have an easy function/method that will convert my numbers (including negative) to something I can calculate with?

Answer

Rakesh picture Rakesh · Jan 30, 2018

looks like you have a problem with the minus('-') symbol in the string.

Try:

def make_float(num):
    num = num.replace(' ','').replace(',','.').replace("−", "-")
    return float(num)