MODULE 2.5: STRING MANIPULATION & REGEX - 10 REAL-WORLD EXAMPLES IN PANDAS

Master Pandas' built-in `.str` accessor methods and regular expressions (Regex) to clean, parse, extract, and transform messy text columns into structured datasets.

💡 Why String & Regex Processing Matters in Pandas

Real-world text data is notoriously messy. User inputs contain extra whitespaces, mixed casing, typos, embedded symbols, and unstructured formatting. Pandas provides the .str accessor, which vectorizes standard Python string operations across millions of rows instantly, combined with full Regular Expression (Regex) support for pattern extraction.

1. Lowercasing and Stripping Whitespaces
Standardizing customer names or category tags by removing leading/trailing spaces and converting all characters to lowercase.
Python (clean_whitespace.py)
import pandas as pd

def clean_text_columns():
    data = {'Customer': ['  Alice Smith ', 'BOB JONES ', 'charlie brown  ']}
    df = pd.DataFrame(data)
    
    df['Clean_Name'] = df['Customer'].str.strip().str.lower()
    print(df.to_string(index=False))

clean_text_columns()
Output: Customer Clean_Name Alice Smith alice smith BOB JONES bob jones charlie brown charlie brown
2. Checking for Substrings with `.str.contains()`
Filtering e-commerce product catalogs to find items containing specific keywords (e.g., finding all "Wireless" devices).
Python (substring_filter.py)
import pandas as pd

def filter_by_keyword():
    data = {'Product': ['Wireless Mouse', 'USB Cable', 'Wireless Keyboard', 'HDMI Adapter']}
    df = pd.DataFrame(data)
    
    # Filter products containing 'Wireless' (case-insensitive)
    wireless_items = df[df['Product'].str.contains('wireless', case=False, na=False)]
    print(wireless_items.to_string(index=False))

filter_by_keyword()
Output: Product Wireless Mouse Wireless Keyboard
3. Replacing Substrings and Currency Symbols
Removing currency symbols ($ and commas) from price strings so they can be converted into numerical floats.
Python (clean_currency.py)
import pandas as pd

def clean_price_column():
    data = {'Item': ['Laptop', 'Phone', 'Monitor'], 'Price': ['$1,250.00', '$850.50', '$320.00']}
    df = pd.DataFrame(data)
    
    # Remove '$' and ',' then convert to float
    df['Price_Clean'] = df['Price'].str.replace('$', '', regex=False).str.replace(',', '', regex=False).astype(float)
    print(df[['Item', 'Price_Clean']])

clean_price_column()
Output: Item Price_Clean 0 Laptop 1250.00 1 Phone 850.50 2 Monitor 320.00
4. Extracting Domain Names from Emails Using Regex
Using Regex capture groups with `.str.extract()` to parse email domains (e.g., gmail.com, corporate.org) from customer email addresses.
Python (extract_domains.py)
import pandas as pd

def extract_email_domains():
    data = {'Email': ['alice@gmail.com', 'bob@yahoo.com', 'charlie@enterprise.org']}
    df = pd.DataFrame(data)
    
    # Extract text after '@' symbol
    df['Domain'] = df['Email'].str.extract(r'@([a-zA-Z0-9.-]+)')
    print(df.to_string(index=False))

extract_email_domains()
Output: Email Domain alice@gmail.com gmail.com bob@yahoo.com yahoo.com charlie@enterprise.org enterprise.org
5. Splitting Full Names into First and Last Names
Splitting a combined name column into separate First Name and Last Name columns using `.str.split(expand=True)`.
Python (split_names.py)
import pandas as pd

def split_full_names():
    data = {'Full_Name': ['John Doe', 'Jane Smith', 'Alex Johnson']}
    df = pd.DataFrame(data)
    
    # Split by space into two new columns
    df[['First_Name', 'Last_Name']] = df['Full_Name'].str.split(' ', expand=True)
    print(df[['First_Name', 'Last_Name']])

split_full_names()
Output: First_Name Last_Name 0 John Doe 1 Jane Smith 2 Alex Johnson
6. Masking Sensitive Data (Credit Card / SSN Redaction)
Using Regex to redact sensitive personal information, keeping only the last 4 digits visible.
Python (mask_data.py)
import pandas as pd

def mask_card_numbers():
    data = {'User': ['Alice', 'Bob'], 'Card': ['4111-2222-3333-4444', '5555-6666-7777-8888']}
    df = pd.DataFrame(data)
    
    # Replace all digits except the last 4 with '*'
    df['Masked_Card'] = df['Card'].str.replace(r'\d{4}-\d{4}-\d{4}-', '****-****-****-', regex=True)
    print(df[['User', 'Masked_Card']])

mask_card_numbers()
Output: User Masked_Card 0 Alice *****-****-****-4444 1 Bob *****-****-****-8888
7. Extracting Product SKU Codes
Isolating alphanumeric SKU codes embedded inside messy descriptive text strings.
Python (extract_sku.py)
import pandas as pd

def extract_sku_codes():
    data = {'Description': ['Order #1029: SKU-9921-A', 'Shipped item SKU-4412-B via FedEx', 'Ref: SKU-8819-C']}
    df = pd.DataFrame(data)
    
    # Extract SKU pattern (e.g., SKU-XXXX-X)
    df['SKU'] = df['Description'].str.extract(r'(SKU-\d{4}-[A-Z])')
    print(df[['Description', 'SKU']])

extract_sku_codes()
Output: Description SKU 0 Order #1029: SKU-9921-A SKU-9921-A 1 Shipped item SKU-4412-B via FedEx SKU-4412-B 2 Ref: SKU-8819-C SKU-8819-C
8. Cleaning Phone Numbers with Regex Substitution
Normalizing various phone number formats by removing parentheses, dashes, and periods into a unified format.
Python (clean_phones.py)
import pandas as pd

def clean_phone_numbers():
    data = {'Phone': ['(555) 123-4567', '555.987.6543', '555 246 8101']}
    df = pd.DataFrame(data)
    
    # Remove all non-digit characters
    df['Phone_Digits'] = df['Phone'].str.replace(r'\D', '', regex=True)
    print(df)

clean_phone_numbers()
Output: Phone Phone_Digits 0 (555) 123-4567 5551234567 1 555.987.6543 5559876543 2 555 246 8101 5552468101
9. Counting Specific Character Occurrences in Text
Counting how many times a particular character or hashtag appears in social media post strings.
Python (count_chars.py)
import pandas as pd

def count_hashtags():
    data = {'Post': ['Python #ai #pandas', 'Data #science #python #ml', 'Hello world']}
    df = pd.DataFrame(data)
    
    # Count occurrences of '#' character
    df['Hashtag_Count'] = df['Post'].str.count('#')
    print(df)

count_hashtags()
Output: Post Hashtag_Count 0 Python #ai #pandas 2 1 Data #science #python #ml 3 2 Hello world 0
10. Conditional String Replacement & Categorization
Categorizing customer feedback text based on keyword presence using regex filtering and conditional string assignment.
Python (feedback_classifier.py)
import pandas as pd

def classify_feedback():
    data = {'Feedback': ['Great service!', 'Terrible product quality', 'Average experience', 'Amazing support!']}
    df = pd.DataFrame(data)
    
    # Classify sentiment based on keywords
    is_positive = df['Feedback'].str.contains('great|amazing|love', case=False, na=False)
    df['Sentiment'] = 'Neutral'
    df.loc[is_positive, 'Sentiment'] = 'Positive'
    
    is_negative = df['Feedback'].str.contains('terrible|bad|poor', case=False, na=False)
    df.loc[is_negative, 'Sentiment'] = 'Negative'
    
    print(df)

classify_feedback()
Output: Feedback Sentiment 0 Great service! Positive 1 Terrible product quality Negative 2 Average experience Neutral 3 Amazing support! Positive