w3resource

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


Pandas: Data Cleaning and Preprocessing Exercise-9 with Solution


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.

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.