Bird
Raised Fist0
Data Analysis Pythondata~20 mins

Extracting with str.extract (regex) in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Regex Extraction Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this code using str.extract?
Given the pandas Series with mixed strings, what will be the output of extracting the first number using regex?
Data Analysis Python
import pandas as pd
s = pd.Series(['apple 123', 'banana 456', 'cherry 789'])
result = s.str.extract(r'(\d+)')
print(result)
A
       0
0    123
1    456
2    789
B
       0
0  apple
1  banana
2  cherry
C
Empty DataFrame
Columns: []
Index: [0, 1, 2]
D
0    123
1    456
2    789
dtype: object
Attempts:
2 left
💡 Hint
Remember str.extract returns a DataFrame with matched groups as columns.
❓ data_output
intermediate
1:30remaining
How many rows have a match in this extraction?
Using str.extract with this regex, how many rows will have a non-null value?
Data Analysis Python
import pandas as pd
s = pd.Series(['cat123', 'dog', 'bird456', 'fish'])
result = s.str.extract(r'(\d+)')
count = result[0].notnull().sum()
print(count)
A1
B3
C4
D2
Attempts:
2 left
💡 Hint
Check which strings contain digits.
🔧 Debug
advanced
2:00remaining
What error does this code raise?
What error will this code raise when trying to extract with an invalid regex pattern?
Data Analysis Python
import pandas as pd
s = pd.Series(['abc123', 'def456'])
result = s.str.extract(r'(\d++')
print(result)
AAttributeError: 'Series' object has no attribute 'str'
Bre.error: missing ), unterminated subpattern at position 4
CTypeError: expected string or bytes-like object
DKeyError: 0
Attempts:
2 left
💡 Hint
Look carefully at the regex pattern syntax.
🚀 Application
advanced
2:30remaining
Extract date components from strings
Given a Series of date strings like '2023-06-15', which option correctly extracts year, month, and day into separate columns?
Data Analysis Python
import pandas as pd
s = pd.Series(['2023-06-15', '2024-01-30', '2022-12-05'])
result = s.str.extract(r'(\d{4})-(\d{2})-(\d{2})')
print(result)
A
       0
0  2023-06-15
1  2024-01-30
2  2022-12-05
B
0    2023-06-15
1    2024-01-30
2    2022-12-05
dtype: object
C
       0   1   2
0  2023  06  15
1  2024  01  30
2  2022  12  05
D
Empty DataFrame
Columns: []
Index: [0, 1, 2]
Attempts:
2 left
💡 Hint
Each pair of parentheses captures one group as a column.
🧠 Conceptual
expert
1:30remaining
Why does str.extract return a DataFrame instead of a Series?
Choose the best explanation for why pandas str.extract returns a DataFrame even when extracting a single group.
ABecause regex groups can be multiple, so str.extract always returns a DataFrame with one column per group for consistency.
BBecause str.extract only works on DataFrames, not Series.
CBecause pandas Series cannot hold string data, so DataFrame is used instead.
DBecause the output must always be numeric, and DataFrame enforces this.
Attempts:
2 left
💡 Hint
Think about how many groups regex can capture.

Practice

(1/5)
1. What does the str.extract method do in pandas when used with a regex pattern?
easy
A. It replaces matching text with a new string.
B. It deletes rows that don't match the pattern.
C. It pulls out matching parts of text into a new DataFrame.
D. It counts how many times the pattern appears.

Solution

  1. Step 1: Understand str.extract purpose

    The method is designed to find parts of text that match a regex pattern and extract them.
  2. Step 2: Check what it returns

    It returns a new DataFrame with the extracted groups or NaN if no match is found.
  3. Final Answer:

    It pulls out matching parts of text into a new DataFrame. -> Option C
  4. Quick Check:

    str.extract extracts text parts [OK]
Hint: Remember: extract pulls out text pieces using patterns [OK]
Common Mistakes:
  • Thinking it deletes rows instead of extracting text
  • Confusing extract with replace or count methods
  • Expecting a single string instead of a DataFrame
2. Which of the following is the correct syntax to extract a 3-digit number from a pandas Series df['code'] using str.extract?
easy
A. df['code'].str.extract('\d{3}')
B. df['code'].str.extract(r'(\d{3})')
C. df['code'].str.extract(r'\d{3}')
D. df['code'].str.extract('(\d{3})')

Solution

  1. Step 1: Identify correct regex string format

    Regex pattern must be a raw string (r'...') to handle backslashes properly.
  2. Step 2: Check parentheses for capturing group

    Parentheses are needed to capture the group to extract.
  3. Final Answer:

    df['code'].str.extract(r'(\d{3})') -> Option B
  4. Quick Check:

    Use raw string with parentheses for capture [OK]
Hint: Use raw string and parentheses for capture groups [OK]
Common Mistakes:
  • Missing parentheses around the pattern
  • Not using raw string causing escape errors
  • Using double backslashes incorrectly
3. Given the following code:
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?
medium
A. [NaN, NaN, NaN, NaN]
B. ['ID123', 'ID456', 'NoID', 'ID789']
C. ['123', '456', 'NoID', '789']
D. ['123', '456', NaN, '789']

Solution

  1. Step 1: Understand the regex pattern

    The pattern 'ID(\d{3})' looks for 'ID' followed by exactly 3 digits and extracts the digits.
  2. Step 2: Apply extraction to each row

    'ID123' -> '123', 'ID456' -> '456', 'NoID' -> no match so NaN, 'ID789' -> '789'.
  3. Final Answer:

    ['123', '456', NaN, '789'] -> Option D
  4. Quick Check:

    Extract digits after 'ID' or NaN if no match [OK]
Hint: Extracted groups appear; no match gives NaN [OK]
Common Mistakes:
  • Expecting full string instead of just digits
  • Not realizing unmatched rows become NaN
  • Confusing extracted text with original
4. Consider this code snippet:
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?
medium
A. The regex pattern lacks parentheses for capturing groups.
B. The regex pattern is invalid syntax.
C. The DataFrame column name is incorrect.
D. str.extract cannot extract digits.

Solution

  1. Step 1: Check regex pattern for capture groups

    str.extract requires parentheses to capture groups; '\d{3}' has none.
  2. Step 2: Understand effect of missing parentheses

    Without parentheses, str.extract returns NaN for all rows because no group is captured.
  3. Final Answer:

    The regex pattern lacks parentheses for capturing groups. -> Option A
  4. Quick Check:

    Parentheses needed to capture groups [OK]
Hint: Always use parentheses to capture groups in str.extract [OK]
Common Mistakes:
  • Forgetting parentheses around regex group
  • Assuming str.extract works without capture groups
  • Confusing str.extract with str.contains
5. You have a DataFrame 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?
hard
A. r'Order: #(\d+), Date: (\d{4}-\d{2}-\d{2})'
B. r'Order: #(\d+), Date: \d{4}-\d{2}-\d{2}'
C. r'Order: #\d+, Date: (\d{4}-\d{2}-\d{2})'
D. r'Order: #(\d+), Date: (\d{4}/\d{2}/\d{2})'

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    r'Order: #(\d+), Date: (\d{4}-\d{2}-\d{2})' -> Option A
  4. Quick Check:

    Two capture groups matching order and date format [OK]
Hint: Use parentheses for each part you want to extract [OK]
Common Mistakes:
  • Missing parentheses around one or both groups
  • Wrong date format with slashes instead of dashes
  • Not capturing order number digits
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard