Validating String length in a column using Pandas
11. Validating String Length in a DataFrame Column
Write a Pandas program that validates string length in a DataFrame column.
Following exercise validate all strings in a column meet a minimum length requirement using str.len().
Sample Solution :
Code :
import pandas as pd
# Create a sample DataFrame with name data
df = pd.DataFrame({
'Name': ['Andrea', 'Rasim', 'Tim', 'Fester']
})
# Validate that all names have a minimum length of 4
valid_names = df['Name'].str.len() >= 4
# Output the result
print(valid_names)
Output:
0 True 1 True 2 False 3 True Name: Name, dtype: bool
Explanation:
- Created a DataFrame with names of varying lengths.
- Used str.len() to check that all names have a minimum length of 4 characters.
- Outputted a Boolean Series indicating whether each name meets the length requirement.
For more Practice: Solve these Related Problems:
- Write a Pandas program to validate that all strings in a column have a minimum length and output rows that do not meet the criteria.
- Write a Pandas program to check that the string length in a column falls within a specific range and list the offending rows.
- Write a Pandas program to trim strings in a column to a maximum length and validate the transformation.
- Write a Pandas program to validate string lengths in a column and create a new column indicating if the length is within the desired range.
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.