Editor

Fix the String Extraction Bug

Intermediate · Fix the bug · from Pandas String and DateTime Operations for Real-World Data

From the lesson: Pandas String and DateTime Operations for Real-World Data

Real-world data is messy. Names arrive in ALL CAPS, dates come as random text strings like "Jan 5, 2024" or "2024/01/05", and phone numbers have dashes in some rows but not others. Before you can analyze anything, you need to clean this stuff up.

Read the lesson

This code tries to extract area codes from phone numbers, but the regex pattern is wrong. Fix the str.extract() call so it correctly pulls out the 3-digit area code from the parentheses.

Print the extracted area codes as a list.

import pandas as pd
phones = pd.Series(['(212) 555-1234', '(415) 555-5678', '(310) 555-9012'])
# Bug: wrong regex pattern
area_codes = phones.str.extract(r'(\d+)')
print(area_codes[0].tolist())

More Pandas String and Datetime exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz