Convert String to Float in a CSV File in Python

This guide discusses how to convert a string column to float through examples in CSV using Python. These examples cover how to use pandas and csv packages in the conversion.

We will save the following data in employees-salaries.csv and use it in our examples.

"FName","LName","Salary","Increment","New Salary"
"Bob","Smith","3,000","0.12","3,360"
"Lewis","Walker","5,600","0.09","6,104"
"Deborah" ,"Shawn","12,100","0.14","13,794"
"Smith","Rowe","2,800","0.08","3,024"
"Kael","Fernandez","7,200","0.10","7,920"

Example 1: Convert a Single String Column in a CSV File into Float Using Pandas

Given a pandas data frame, df, you can convert a column into a float using the following line:

The following example converts the New Salary column in the CSV data given above into float. The pre-requisite is to remove commas in the numbers before doing the conversion.

Output:

New Salary column before conversion:  object
New Salary column after conversion:  float64

Example 2: Convert Multiple Columns in a CSV File into Float Using Pandas

Given a data frame named df, you can convert multiple columns into float using the line below:

Here is an example of converting the Salary and New Salary columns.

Example 3: Convert String Column (s) into a Numeric Using pandas.to_numeric() Function

The pandas.to_numeric() function converts a column into an integer or float based on input. The general syntax for the function is as follows.

Here is an example of how to use it to convert the New Salary Column.

Output:

FName          object
LName          object
Salary         object
Increment     float64
New Salary      int64

Then you can apply pandas.to_numeric() on multiple columns using the code below.

Output:

FName          object
LName          object
Salary        float64
Increment     float64
New Salary    float64

Example 4: Convert String Column(s) to Floats Using the CSV Package

This method iterates through the CSV rows and converts column(s) to float based on the index.