close

[Solved] Cannot convert string to float in pandas (ValueError)

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Cannot convert string to float in pandas (ValueError) in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Cannot convert string to float in pandas (ValueError) Error Occurs?

Today I get the following error Cannot convert string to float in pandas (ValueError) in python.

How To Solve Cannot convert string to float in pandas (ValueError) Error ?

  1. How To Solve Cannot convert string to float in pandas (ValueError) Error ?

    To Solve Cannot convert string to float in pandas (ValueError) Error These strings have commas as thousands separators so you will have to remove them before the call to float:

  2. Cannot convert string to float in pandas (ValueError)

    To Solve Cannot convert string to float in pandas (ValueError) Error These strings have commas as thousands separators so you will have to remove them before the call to float:

Solution 1

Another solution with list comprehension, if need apply string functions working only with Series (columns of DataFrame) like str.split and str.replace:

df = pd.concat([df[col].str.split()
                       .str[0]
                       .str.replace(',','').astype(float) for col in df], axis=1)

#if need convert column Purchase count to int
df['Purchase count'] = df['Purchase count'].astype(int)
print (df)
         Total Revenue  Average Revenue  Purchase count  Rate
Date                                                        
Monday         1304.4            20.07            2345  1.54

Solution 2

These strings have commas as thousands separators so you will have to remove them before the call to float:

df[column] = (df[column].str.split()).apply(lambda x: float(x[0].replace(',', '')))

This can be simplified a bit by moving split inside the lambda:

df[column] = df[column].apply(lambda x: float(x.split()[0].replace(',', '')))

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read