Validating Data Type of a Specific Column in Pandas
3. Validating the Data Type of a Specific Column
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.
For more Practice: Solve these Related Problems:
- Write a Pandas program to validate that a specific column contains only numeric values and report any violations.
- Write a Pandas program to check the data type of a specific column and convert it if it does not match the expected type.
- Write a Pandas program to validate a specific column's data type and output the rows that fail the validation.
- Write a Pandas program to enforce a custom data type for a specific column and generate warnings for non-compliant entries.
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.