Home > database >  ValueError: could not convert string to float: '1.318.21''
ValueError: could not convert string to float: '1.318.21''

Time:10-01

i'm trying to convert data type from object to float, however when I try to convert it shows the error message:

ValueError: could not convert string to float: '1.318.21'

Here is the code:

profkes_na=profkes_df.fillna(0)
profkes_decimal=profkes_na.stack().str.replace(',','.').unstack()
profkes_float=profkes_decimal.astype('float')

Thank you.

CodePudding user response:

change : profkes_decimal=profkes_na.stack().str.replace(',','.').unstack() to : profkes_decimal=profkes_na.stack().str.replace(',','').unstack()

CodePudding user response:

It's unclear from the question what modules are being used. In pure Python one could do this:

s = '1.318.21'

def asfloat(s):
    if (ndp := s.count('.')) > 1:
        s = s.replace('.', '', ndp-1)
    return float(s)

print(asfloat(s))
  • Related