We use str.extract to pull out specific parts of text from data using patterns. It helps us find and save useful pieces from messy text.
Extracting with str.extract (regex) in Data Analysis Python
Series.str.extract(pat, flags=0, expand=True)
pat is the pattern you want to find, written as a regular expression (regex).
If expand=True, the result is a DataFrame; if False, it returns a Series.
df['phone'].str.extract(r'(\d{3})')
df['text'].str.extract(r'(\d{4}-\d{2}-\d{2})')
df['email'].str.extract(r'([^@]+)@')
This code creates a small table with messages. It then extracts area codes, dates, and email usernames using str.extract with regex patterns.
import pandas as pd data = {'messages': ['Call me at 415-555-1234', 'My birthday is 1990-05-21', 'Email: user@example.com']} df = pd.DataFrame(data) # Extract area code (3 digits) from phone numbers area_codes = df['messages'].str.extract(r'(\d{3})') # Extract date in YYYY-MM-DD format dates = df['messages'].str.extract(r'(\d{4}-\d{2}-\d{2})') # Extract username from email usernames = df['messages'].str.extract(r'([\w\.]+)@') print('Area Codes:') print(area_codes) print('\nDates:') print(dates) print('\nUsernames:') print(usernames)
Regex patterns use special symbols to match text. For example, \d means any digit.
If no match is found, str.extract returns NaN for that row.
Use parentheses () in regex to capture the part you want to extract.
str.extract helps pull out parts of text using patterns.
It returns a new table with the extracted pieces or NaN if nothing matches.
Useful for cleaning and organizing messy text data.
Practice
str.extract method do in pandas when used with a regex pattern?Solution
Step 1: Understand str.extract purpose
The method is designed to find parts of text that match a regex pattern and extract them.Step 2: Check what it returns
It returns a new DataFrame with the extracted groups or NaN if no match is found.Final Answer:
It pulls out matching parts of text into a new DataFrame. -> Option CQuick Check:
str.extract extracts text parts [OK]
- Thinking it deletes rows instead of extracting text
- Confusing extract with replace or count methods
- Expecting a single string instead of a DataFrame
df['code'] using str.extract?Solution
Step 1: Identify correct regex string format
Regex pattern must be a raw string (r'...') to handle backslashes properly.Step 2: Check parentheses for capturing group
Parentheses are needed to capture the group to extract.Final Answer:
df['code'].str.extract(r'(\d{3})') -> Option BQuick Check:
Use raw string with parentheses for capture [OK]
- Missing parentheses around the pattern
- Not using raw string causing escape errors
- Using double backslashes incorrectly
import pandas as pd
df = pd.DataFrame({'text': ['ID123', 'ID456', 'NoID', 'ID789']})
df['number'] = df['text'].str.extract(r'ID(\d{3})')What will be the content of the new column
number?Solution
Step 1: Understand the regex pattern
The pattern 'ID(\d{3})' looks for 'ID' followed by exactly 3 digits and extracts the digits.Step 2: Apply extraction to each row
'ID123' -> '123', 'ID456' -> '456', 'NoID' -> no match so NaN, 'ID789' -> '789'.Final Answer:
['123', '456', NaN, '789'] -> Option DQuick Check:
Extract digits after 'ID' or NaN if no match [OK]
- Expecting full string instead of just digits
- Not realizing unmatched rows become NaN
- Confusing extracted text with original
import pandas as pd
df = pd.DataFrame({'info': ['abc123', 'def456', 'ghi789']})
df['extracted'] = df['info'].str.extract('\d{3}')What is the issue with this code?
Solution
Step 1: Check regex pattern for capture groups
str.extract requires parentheses to capture groups; '\d{3}' has none.Step 2: Understand effect of missing parentheses
Without parentheses, str.extract returns NaN for all rows because no group is captured.Final Answer:
The regex pattern lacks parentheses for capturing groups. -> Option AQuick Check:
Parentheses needed to capture groups [OK]
- Forgetting parentheses around regex group
- Assuming str.extract works without capture groups
- Confusing str.extract with str.contains
df with a column 'data' containing strings like 'Order: #12345, Date: 2023-05-10'. You want to extract the order number and date into separate columns using str.extract. Which regex pattern correctly extracts both parts?Solution
Step 1: Identify needed capture groups
We need to capture order number digits and date in 'YYYY-MM-DD' format, so two groups are required.Step 2: Check regex pattern correctness
r'Order: #(\d+), Date: (\d{4}-\d{2}-\d{2})' has two groups: '(\d+)' for order number and '(\d{4}-\d{2}-\d{2})' for date, matching the format exactly.Final Answer:
r'Order: #(\d+), Date: (\d{4}-\d{2}-\d{2})' -> Option AQuick Check:
Two capture groups matching order and date format [OK]
- Missing parentheses around one or both groups
- Wrong date format with slashes instead of dashes
- Not capturing order number digits
Ready to prove it?
Pass the test and this pattern moves unknown
