pythonbeginner
Pandas String Operations
Clean, extract, and transform string columns using pandas .str accessor methods.
pythonPress ⌘/Ctrl + Shift + C to copy
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.
pythonbeginner
Pandas Null Handling Strategies
Comprehensive strategies for detecting, filling, and handling missing values in pandas DataFrames.
Best for: Cleaning datasets with missing values
#pandas#null
pythonbeginner
Polars String Operations
Use the Polars .str namespace for fast, vectorised string cleaning and extraction.
Best for: data cleaning
#polars#strings
pythonbeginner
Detect & Remove Pandas Duplicates
Find, count, and remove duplicate rows with flexible keep strategy and composite key support.
Best for: data cleaning
#pandas#duplicates
pythonbeginner
Pandas DataFrame Transformations
Common pandas DataFrame transformations including column operations, type casting, and string methods.
Best for: Cleaning raw data files for analysis
#pandas#dataframe