String conversion error for float in python

I'm new to Python, so forgive me for this simple question. I am trying to convert a string to float. Here is an example of data:

0     10.65%
1      7.90%

When I try:

 df['int_rate'] = df['int_rate'].astype('float')

I get:

ValueError: could not convert string to float: '13.75%'

When I try:

df['int_rate'] = df['int_rate'].replace("%","", inplace=True) 

And check my details, I get:

0     None
1     None

Any ideas what I'm doing wrong? Many thanks!

+6
source share
3 answers

You can use Series.replacewith parameter regex=Trueto replace substrings:

df = pd.DataFrame({'int_rate':['10.65%','7.90%']})
df['int_rate'] = df['int_rate'].replace("%","", regex=True).astype(float)
print (df)
   int_rate
0     10.65
1      7.90

Or Series.str.replace:

df['int_rate'] = df['int_rate'].str.replace("%","")
print (df)
  int_rate
0    10.65
1     7.90
2         

Or Series.str.rstrip:

df['int_rate'] = df['int_rate'].str.rstrip("%").astype(float)
print (df)
   int_rate
0     10.65
1      7.90

See the difference without it:

df = pd.DataFrame({'int_rate':['10.65%','7.90%', '%']})

df['int_rate_subs'] = df['int_rate'].replace("%","", regex=True)
df['int_rate_val'] = df['int_rate'].replace("%","")
print (df)
  int_rate int_rate_subs int_rate_val
0   10.65%         10.65       10.65%
1    7.90%          7.90        7.90%
2        %                           
+3
source

As you might have guessed, it ValueError: could not convert string to float: '13.75%'indicates that the symbol %blocks the conversion.

Now when you try to remove it:

df['int_rate'] = df['int_rate'].replace("%","", inplace=True) 

inplace=True , , , , replace() None. , None df['int_rate'] , None. :

df['int_rate'] = df['int_rate'].replace("%","") 

df['int_rate'].replace("%","", inplace=True)
+5

Since you are using a string, you can convert the value to float using

float(df['int_rate'][:-1])

This reads the line from the first position to the second to the last position, 10.65 instead of 10.65%.

+2
source

All Articles