w3resource

Validating Data Type of a Specific Column in Pandas

Pandas: Data Validation Exercise-3 with Solution

Write a Pandas program to validate the data type of a specific column in a DataFrame.

This exercise demonstrates how to validate the data type of a specific column using astype().

Sample Solution :

Code :

import pandas as pd

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

# Check if the 'Price' column can be converted to float
try:
    df['Price'] = df['Price'].astype(float)
    print("Data type conversion successful.")
except ValueError:
    print("Data type conversion failed.")

Output:

Data type conversion successful

Explanation:

  • Created a DataFrame where the 'Price' column is in string format.
  • Attempted to convert the 'Price' column to float using astype().
  • Used try-except to handle any data type conversion errors, outputting success or failure messages.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/pandas/pandas-validate-data-type-conversion-of-a-specific-column.php