3.1 C
London
Friday, December 20, 2024
HomePandas in PythonDataFrame Functions in PythonHow to Convert Strings to Float in Pandas

How to Convert Strings to Float in Pandas

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following methods to convert a string to a float in pandas:

Method 1: Convert a Single Column to Float

#convert "assists" column from string to float
df['assists'] = df['assists'].astype(float)

Method 2: Convert Multiple Columns to Float

#convert both "assists" and "rebounds" from strings to floats
df[['assists', 'rebounds']] = df[['assists', 'rebounds']].astype(float)

Method 3: Convert All Columns to Float

#convert all columns to float
df = df.astype(float)

The following examples show how to use each method in practice with the following pandas DataFrame:

import numpy as np
import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [np.nan, 12, 15, 14, 19],
                   'assists': ['5', np.nan, '7', '9', '12'],
                   'rebounds': ['11', '8', '10', '6', '6']})  

#view DataFrame
df

 	points	assists	rebounds
0	NaN	5.0	11
1	12.0	NaN	8
2	15.0	7.0	10
3	14.0	9.0	6
4	19.0	12.0	6

#view column data types
df.dtypes

points      float64
assists      object
rebounds     object
dtype: object

Example 1: Convert a Single Column to Float

The following syntax shows how to convert the assists column from a string to a float:

#convert "assists" from string to float
df['assists'] = df['assists'].astype(float)

#view column data types
df.dtypes

points      float64
assists     float64
rebounds     object
dtype: object

Example 2: Convert Multiple Columns to Float

The following syntax shows how to convert both the assists and rebounds columns from strings to floats:

#convert both "assists" and "rebounds" from strings to floats
df[['assists', 'rebounds']] = df[['assists', 'rebounds']].astype(float)

#view column data types
df.dtypes

points      float64
assists     float64
rebounds    float64
dtype: object

Example 3: Convert All Columns to Float

The following syntax shows how to convert all of the columns in the DataFrame to floats:

#convert all columns to float
df = df.astype(float)

#view column data types
df.dtypes

points      float64
assists     float64
rebounds    float64
dtype: object

Bonus: Convert String to Float and Fill in NaN Values

The following syntax shows how to convert the assists column from string to float and simultaneously fill in the NaN values with zeros:

#convert "assists" from string to float and fill in NaN values with zeros
df['assists'] = df['assists'].astype(float).fillna(0)

#view DataFrame
df

        points	assists	rebounds
0	NaN	5.0	11
1	12.0	0.0	8
2	15.0	7.0	10
3	14.0	9.0	6
4	19.0	12.0	6

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

Pandas: How to Convert object to int
Pandas: How to Convert Floats to Integers
Pandas: How to Convert Specific Columns to NumPy Array

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories