w3resource

Converting Data Types in a DataFrame Using astype() in Pandas


9. Replacing Missing Data with Mean Value

Write a Pandas program to convert data types using astype().

In this exercise, we have converted the data types of columns in a DataFrame using the astype() method.

Sample Solution :

Code :

import pandas as pd

# Create a sample DataFrame with mixed types
df = pd.DataFrame({
    'ID': ['1', '2', '3'],
    'Price': ['10.5', '20.0', '30.5']
})

# Convert 'ID' to integer and 'Price' to float
df['ID'] = df['ID'].astype(int)
df['Price'] = df['Price'].astype(float)

# Output the result
print(df)

Output:

   ID  Price
0   1   10.5
1   2   20.0
2   3   30.5

Explanation:

  • Created a DataFrame with columns in string format.
  • Used astype() to convert 'ID' to integer and 'Price' to float.
  • Returned the DataFrame with updated data types.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to replace missing values in a numeric column with the mean of that column.
  • Write a Pandas program to replace missing values in several columns with their respective means simultaneously.
  • Write a Pandas program to perform mean imputation and then validate the replacement by comparing before-and-after statistics.
  • Write a Pandas program to visualize the effect of mean imputation on the distribution of a numeric column.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.