pythonbeginner

Pandas String Operations

Clean, extract, and transform string columns using pandas .str accessor methods.

python
import pandas as pd

df = pd.DataFrame({'raw': ['  Alice Smith ', 'bob@EXAMPLE.com', 'New York, NY 10001', None]})

df['clean']    = df['raw'].str.strip().str.lower()
df['has_at']   = df['raw'].str.contains('@', na=False)
df['city']     = df['raw'].str.extract(r'^([^,]+),')[0]
df['zip']      = df['raw'].str.extract(r'(\d{5})$')[0]
df['replaced'] = df['raw'].str.replace(r'\s+', ' ', regex=True)
print(df)

Use Cases

  • data cleaning
  • text extraction
  • normalisation

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.