Home > database >  ValueError: could not convert string to float in pandas when using astype
ValueError: could not convert string to float in pandas when using astype

Time:09-29

so this is the line that is getting the error :

footballers['Value (M)'] = footballers['Value (M)'].astype(float)

where the footballers[] is defined as:

footballers['Value (M)'] = np.where(footballers['Unit'] == '0', 0, 
                                footballers['Value'].str[1:-1].replace(r'[a-zA-Z]',''))

The error which i am getting is :

ValueError: could not convert string to float:

CodePudding user response:

Maybe in the value of footballers, there are some other characters like _ (underscore), - (dash), which keeps the string not "float convertible".

CodePudding user response:

If your leading and trailing characters footballers['Value'].str[0] and footballers['Value'].str[-1] are not digits, the conversion to float will fail.

Try:

footballers['Value (M)'] = footballers['Value (M)'].str[1:-1].astype(float)

If this fails again, try to find bad rows

footballers.loc[pd.to_numeric(footballers['Value (M)'], errors='coerce').isna(),
                'Value (M)']
  • Related