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.
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://198.211.115.131/python-exercises/pandas/pandas-validate-string-length-in-a-column.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics