w3resource

Validating String length in a column using Pandas


Pandas: Data Validation Exercise-11 with Solution


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.

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.