Python / Data Science Essentials Interview Questions
How do you perform string operations on Pandas DataFrame columns?
Pandas exposes string methods through the .str accessor on object-dtype Series. These operations are vectorised over the whole column — no explicit loop needed — and handle NaN values gracefully (they propagate as NaN rather than raising an error).
import pandas as pd df = pd.DataFrame({'name': [' Alice Smith ', 'bob jones', 'CAROL LEE', None], 'email': ['alice@corp.com', 'BOB@CORP.COM', 'carol@other.org', None]}) # Case normalisation df['name'].str.strip().str.title() # 'Alice Smith', 'Bob Jones', 'Carol Lee', NaN # Split into multiple columns df[['first', 'last']] = df['name'].str.strip().str.split(' ', expand=True) # Contains / startswith / endswith df[df['email'].str.endswith('@corp.com', na=False)] # Extract patterns with regex df['domain'] = df['email'].str.extract(r'@(.+)$') # captures text after @ # Replace with regex df['email'].str.lower().str.replace(r'[^a-z0-9@._]', '', regex=True) # Count occurrences df['name'].str.count('l') # 1, 0, 1, NaN # Length df['name'].str.len() # Padding / justification df['id'].str.zfill(6) # zero-pad to width 6 df['name'].str.ljust(20, '-') # left-justify, pad with dashes
The na=False argument in methods like str.contains and str.startswith is important — without it, NaN values produce NaN in the boolean mask, which causes issues in filtering. Passing na=False returns False for NaN rows, keeping them out of the filtered result cleanly.
More Related questions...