Data Analysis with Python (pandas, polars, DuckDB) Module 9 – Text extraction and categorical data
Extracting fields from text with regular expressions
Extract PIN codes, phone numbers and bank codes from text with pandas str.extract, check each value against the rules and a directory, and count failures.
What you will learn
- Test and extract patterns with str.contains, str.extract and str.extractall
- Write and validate patterns for Indian formats such as PIN codes, mobile numbers and IFSC codes
- Explain which methods treat a pattern as a regular expression by default in pandas, polars and DuckDB
- Count and inspect extraction failures, then check extracted values against a reference list
Before you start
What you’ll learn · Before you start
What you will learn
- Test and extract patterns with str.contains, str.extract and str.extractall
- Write and validate patterns for Indian formats such as PIN codes, mobile numbers and IFSC codes
- Explain which methods treat a pattern as a regular expression by default in pandas, polars and DuckDB
- Count and inspect extraction failures, then check extracted values against a reference list
Before you start
On this page
People type values into text fields that were meant to hold more than one fact: a delivery address with the PIN
code somewhere inside it, a contact note with a phone number and a bank code, a product name with a size. A
regular expression: A pattern language for matching text. The selected engine and method define its character classes, boundaries and returned matches. (a regex) describes what such a value looks like, for example “six digits with no other digit
beside them”, and pandas applies it to every row of a column. str.contains says whether each row has a match,
str.extract copies the first match of each capture group: A parenthesized part of a regular expression whose matched text can be returned separately from the rest of the match. into a column of its own, and str.extractall returns
every match.
The examples use Indian formats: the six-digit PIN code, the ten-digit mobile number and the 11-character IFSC bank code. Each has a published definition, and the PIN codes have a public directory to check against. The same steps work for postal codes, phone numbers and identifiers anywhere.
The first match needs a declared boundary
Customers of an online shop typed these delivery notes. Every note should contain a PIN code, and several of them hide a trap.
Extraction is only half the work. Some rows will not match and some matches will be wrong, so you also normalise the text first, read and count the failures, check each value’s structure, and then check that the value exists in a reference list.
id,note
D01,"Flat 4B, Sai Residency, Kothrud, Pune 411038"
D02,"Near bus stand, Hubballi - 580020. Call before 6 pm"
D03,"Plot 12, Sector 21, Gurugram 122016 (alt PIN 122001)"
D04,"Old Market Road, Shillong 793 001"
D05,"C-14, Lajpat Nagar, New Delhi 110024"
D06,"Ward 6, Kozhikode 6730O4"
D07,"Banjara Hills, Hyderabad, near the clock tower"
D08,"House 12, Assi Ghat, Varanasi २२१००५"
D09,"Ph 9845012345, MG Road, Bengaluru 560001"
D10,"Anna Nagar, Chennai 600400"
D11,"Salt Lake Sector V, Kolkata, PIN 000000"
D12,"Main Road, Ranchi 834001-34" str.extract takes a pattern with at least one capture group, a part in parentheses, and returns what the group
matched in the first match of each row. The script tries two patterns:
Follow D09 from its phone number to its bounded candidate. Compare 984501 with 560001 before running the same patterns.
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- Read D09. D09 contains phone 9845012345 before Bengaluru's PIN candidate 560001. The order of the text determines which match comes first.
- Loose six digits. The loose six-digit pattern accepts 984501, a prefix of the phone number. Its length alone does not identify the field.
- Word boundaries. Python's word boundaries stop that prefix from matching inside ten digits. The first bounded candidate is 560001.
- Name the output. The named capture group makes a pin column. A note with no match still has an output row with a missing pin.
The named result still keeps one output row per source note. Run the original two-pattern comparison.
# The first match of a pattern, copied into a column of its own with str.extract.
import pandas as pd
notes = pd.read_csv("delivery_notes.csv", dtype="str")
# Six digits anywhere: also matches the first six digits of a phone number.
loose = notes["note"].str.extract(r"(\d{6})", expand=False)
# Six digits with no letter, digit or underscore touching them (\b is a word
# boundary). The named group (?P<pin>...) becomes the column name.
bounded = notes["note"].str.extract(r"(?P<pin>\b\d{6}\b)")
result = notes[["id"]].assign(loose=loose, pin=bounded["pin"])
print(result.to_string(index=False))
print()
print("rows:", len(notes))
print("with a PIN-like match:", notes["note"].str.contains(r"\b\d{6}\b").sum())
print("no match (NaN):", result["pin"].isna().sum())
print("dtype of the new column:", result["pin"].dtype) Output
id loose pin D01 411038 411038 D02 580020 580020 D03 122016 122016 D04 NaN NaN D05 110024 110024 D06 NaN NaN D07 NaN NaN D08 २२१००५ २२१००५ D09 984501 560001 D10 600400 600400 D11 000000 000000 D12 834001 834001 rows: 12 with a PIN-like match: 8 no match (NaN): 3 dtype of the new column: str
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 extract_pins.py
- The loose pattern
(\d{6})takes the first six digits it finds anywhere, so for D09 it returns984501, the start of the phone number, instead of the PIN code560001that follows it. Nothing in the output warns you. - In the second pattern,
\bis a word boundary: A position between a word and a nonword character, or between a word character and an input edge. The engine defines what counts as a word character.: the six digits may not have a letter, a digit or an underscore directly before or after them. A phone number’s digits run on, so it no longer matches, and D09 gets its real PIN code. (?P<pin>…)names the group, and the name becomes the column’s name. An unnamed group gives a column called0.- A row without a match gets a missing value (NaN), never an error. That is why the count of missing values matters: three notes have no six-digit run at all.
- The new column has pandas’
strdtype, so the codes stay text and keep any leading zeros.
The result for D08 deserves a second look. Its PIN code is written in Devanagari digits, २२१००५, and both patterns
extracted it, because in Python’s re module \d means any decimal digit of any script. Yet str.contains with the
same bounded pattern counted only 8 notes with a match, not 9: in pandas 3 with PyArrow installed it runs on another
regex engine, in which \d means only 0 to 9, as the section on regex engines below shows. Later checks, other
engines and most databases expect the ASCII digits 0 to 9, so from here on the patterns write [0-9] when they mean
exactly those ten digits, and digits of other scripts are converted before matching.
Word boundaries are stricter than merely excluding adjacent digits: Python rejects A411038B under this rule. The
same boundary spelling can differ by engine on é411038. Run the boundary cases and inspect the two-code note.
# A digit rule and a word rule are different, even with the same ASCII digits.
import re
import duckdb
import pandas as pd
import polars as pl
notes = ["A411038B", "é411038", "411038_9", "411038,560001", "9845012345"]
pattern = r"\b([0-9]{6})\b"
pandas_notes = pd.Series(notes)
polars_notes = pl.DataFrame({"note": notes})
connection = duckdb.connect()
duck_hits = [
value for (value,) in connection.execute(
"SELECT regexp_extract(note, ?, 1) FROM polars_notes", [pattern]
).fetchall()
]
python_hits = pandas_notes.str.extract(pattern, expand=False)
arrow_hits = pandas_notes.str.contains(pattern.replace("(", "(?:", 1))
polars_hits = polars_notes.select(pl.col("note").str.extract(pattern, 1)).to_series()
print("input | pandas extract | pandas contains | polars extract | DuckDB extract")
for text, python, arrow, polars, duck in zip(
notes, python_hits, arrow_hits, polars_hits, duck_hits
):
python = "-" if pd.isna(python) else python
print(f"{text} | {python} | {bool(arrow)} | {polars or '-'} | {duck or '-'}")
text = "411038,560001"
consuming = r"(?:^|[^0-9])([0-9]{6})(?:[^0-9]|$)"
digit_only = r"(?<![0-9])([0-9]{6})(?![0-9])"
print()
print("consuming a separator:", re.findall(consuming, text))
print("zero-width digit guards:", re.findall(digit_only, text))
print("ASCII runs, then length:", [run for run in re.findall(r"[0-9]+", text) if len(run) == 6])
# Being present in the directory cannot establish what a number meant in a note.
directory = pd.read_parquet("pin_directory.parquet")
note = "Warehouse batch 411 038; deliver to Mumbai 400053"
joined = re.sub(r"\b([0-9]{3}) ([0-9]{3})\b", r"\1\2", note)
candidates = re.findall(r"\b[0-9]{6}\b", joined)
print()
print("after joining digit groups:", candidates)
print("both in this directory:", all(pin in set(directory["pin"]) for pin in candidates)) Output
input | pandas extract | pandas contains | polars extract | DuckDB extract A411038B | - | False | - | - é411038 | - | True | - | 411038 411038_9 | - | False | - | - 411038,560001 | 411038 | True | 411038 | 411038 9845012345 | - | False | - | - consuming a separator: ['411038'] zero-width digit guards: ['411038', '560001'] ASCII runs, then length: ['411038', '560001'] after joining digit groups: ['411038', '400053'] both in this directory: True
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 boundary_cases.py
Consuming the comma between 411038,560001 misses the second value. Python’s zero-width digit guards keep both;
collecting maximal ASCII digit runs and testing their lengths is another way to express that digit-only rule.
Both repaired warehouse and delivery numbers in the final example exist in the snapshot, so directory membership
does not choose the customer’s intended field.
Key idea
Checkpoint
Check: First match and boundaries
Count every match against every source note
D03 gives two PIN codes, 122016 and an alternative, 122001. str.extract returned the first one and said nothing
about the second. str.extractall returns one row per match instead:
Follow D03 into two match rows, then restore counts for every original note. Check why four zero-count rows need reindexing.
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- Read D03. D03 contains 122016 and the alternative 122001. Selecting the first does not establish which address the customer intended.
- Keep both matches. extractall returns two rows under D03, with match numbers 0 and 1. It returns no row for an unmatched note.
- Count by source id. Grouping the matches by id gives the candidate count for each matched source note.
- Restore absent rows. Reindexing onto all twelve note ids restores four zero counts: seven notes have one candidate and D03 has two.
# Every match, not only the first: str.extractall returns one row per match.
import pandas as pd
notes = pd.read_csv("delivery_notes.csv", dtype="str").set_index("id")
matches = notes["note"].str.extractall(r"(?P<pin>\b[0-9]{6}\b)")
print(matches.head(4))
print()
print("index levels:", matches.index.names)
# Candidates per note; notes without any are absent from extractall's result.
per_note = matches.groupby(level="id").size().reindex(notes.index, fill_value=0)
print("candidates per note:", per_note.value_counts().sort_index().to_dict())
print("notes with more than one:", per_note[per_note > 1].index.tolist())
# The first match of each note equals what str.extract returns.
first = matches.xs(0, level="match")["pin"]
extracted = notes["note"].str.extract(r"(?P<pin>\b[0-9]{6}\b)")["pin"].dropna()
print("first matches equal str.extract:", first.equals(extracted)) Output
pin
id match
D01 0 411038
D02 0 580020
D03 0 122016
1 122001
index levels: ['id', 'match']
candidates per note: {0: 4, 1: 7, 2: 1}
notes with more than one: ['D03']
first matches equal str.extract: True
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 all_matches.py
The result has a two-level index: the note’s own index, id, and match, which numbers the matches of each note from
0. A note without any match does not appear at all, which is why the script reindexes the counts against all twelve
notes before counting them. Seven notes hold exactly one candidate, one holds two, and four hold none: D08 is among
them now that the pattern accepts only 0 to 9. The first match of each note equals what str.extract returned. A note
with two candidates is a question for a person, or for a rule you can write down, such as “take the first PIN code
unless the note says alt”; it is not something to settle silently.
Checkpoint
Check: Candidate counts per note
Read the failures before choosing a repair
A pattern that finds a value in most rows looks finished, and that is exactly when people stop. The rows it missed show where its assumptions break, so list them before deciding anything:
Step through D04 and D08’s declared repairs. Keep D06 and D07 visible and verify that ten found plus two missing still equals twelve.
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- Keep four misses. The ASCII pattern misses D04, D06, D07 and D08. A lower miss count is not enough evidence to change the rule.
- Repair D04 and D08. For these notes, joining D04's 793 001 and converting D08's decimal digits recovers 793001 and 221005. Retain the raw text and the repair decision.
- Keep D06 and D07. D06 contains a letter O and D07 has no PIN. Neither gets a guessed replacement from this rule.
- Reconcile all rows. The same twelve rows now contain ten candidates and two misses. Directory validation is a separate later stage.
# Every row the pattern missed, read one by one, and the two repairs that are safe.
import unicodedata
import pandas as pd
notes = pd.read_csv("delivery_notes.csv", dtype="str")
PIN = r"\b([0-9]{6})\b"
first_try = notes["note"].str.extract(PIN, expand=False)
print("missed by the pattern:")
print(notes.loc[first_try.isna(), ["id", "note"]].to_string(index=False))
def ascii_digits(text: str) -> str:
"""Write digits of any script (Devanagari २, Arabic-Indic ٢ ...) as 0-9."""
return "".join(
str(unicodedata.decimal(ch)) if ch.isdecimal() and not ch.isascii() else ch
for ch in text
)
repaired_text = (
notes["note"]
.map(ascii_digits) # repair 1: other scripts' digits
.str.replace(r"\b([0-9]{3}) ([0-9]{3})\b", r"\1\2", regex=True) # repair 2: "793 001"
)
second_try = repaired_text.str.extract(PIN, expand=False)
changed = first_try.isna() & second_try.notna()
found = notes.loc[changed, "id"].tolist()
print()
print("found after the repairs:", found, second_try[changed].tolist())
print("still missing:", notes.loc[second_try.isna(), "id"].tolist())
print(f"rows: {len(notes)}, found first time: {first_try.notna().sum()}, "
f"after repairs: {second_try.notna().sum()}, missing: {second_try.isna().sum()}") Output
missed by the pattern: id note D04 Old Market Road, Shillong 793 001 D06 Ward 6, Kozhikode 6730O4 D07 Banjara Hills, Hyderabad, near the clock tower D08 House 12, Assi Ghat, Varanasi २२१००५ found after the repairs: ['D04', 'D08'] ['793001', '221005'] still missing: ['D06', 'D07'] rows: 12, found first time: 8, after repairs: 10, missing: 2
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 failures.py
Each miss has its own cause, and each cause gets its own decision:
- D04,
793 001. The code is written as three digits, a space and three more, a common way to write PIN codes. For this labelled note, joining its two groups of three digits is the declared repair, followed by the same structure and directory checks. A matching directory entry does not prove what a number meant in arbitrary text. - D08,
२२१००५. The digits are right; only the script differs. Python’sunicodedata.decimalgives the value of any decimal digit, so the repair writes them as221005. - D06,
6730O4. A capital letter O stands where a zero belongs. The fix looks obvious, but turning letters into digits is a guess, and a guessed PIN code sends a parcel to the wrong post office. This note goes back to the customer. - D07. There is no PIN code at all, and no pattern can recover one.
After the two repairs, ten of the twelve notes have a candidate. Report all four numbers the script prints, so that anyone reading the result knows how much of it came from the text as typed and how much from a repair.
Checkpoint
Check: Repair decisions and reconciliation
Check structure and membership separately
Six digits are not yet a PIN code. A value can have the right shape and still be impossible, such as the placeholder
000000, or be possible and still not exist, such as a mistyped 600400. So two checks follow the extraction:
Follow the twelve rows through candidate, shape and snapshot membership checks. Keep each failed status in the final total.
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- Extract candidates. After the declared repairs, ten notes have a candidate and two do not. A missing candidate is counted before a shape check.
- Check whole shape. The full-string six-digit rule rejects D11's 000000. Nine candidates remain well formed.
- Check the snapshot. D10's 600400 is absent from the bundled directory snapshot. The other eight candidates are present; presence does not confirm the address's meaning.
- Count the statuses. Eight ok, two not found, one bad shape and one absent from the snapshot add back to twelve source notes.
From typed text to a checked PIN code
Text description of the diagram
A vertical flow from a typed delivery note to a status for every row, in four steps.
- Normalise the text: digits written in other scripts become the digits 0 to 9, and a PIN code typed with a space after its third digit, such as 793 001, is joined into 793001.
- Extract the first match of the pattern \b([0-9]{6})\b with str.extract: six digits with no digit, letter or underscore next to them.
- Check the structure with str.fullmatch and the pattern [1-9][0-9]{5}: six digits whose first digit is not 0.
- Check that the code exists with isin against the directory's list of PIN codes.
Every row ends with one status: ok, no PIN found, not a valid PIN, or not in the directory. The rows that are not ok are counted and listed, never dropped.
What makes a PIN code
India’s postal code, the Postal Index Number (PIN), has six digits and is written after the name of the town. Read
from the left, the digits narrow the address down, from a region to a sorting and forwarding centre and then to the
delivery post office, as the Universal Postal Union’s addressing guide for India shows. The Department of Posts’ All India Pincode Directory on the Open Government Data Platform India is the attributed
source of the bundled snapshot, under the Government Open Data License – India. The file
pin_directory.parquet holds one row per PIN code of the copy that MySmartCoPilot’s PIN Code Finder uses, with its
districts and states.
# Extract, then check the structure, then check that the PIN code exists.
# pin_directory.parquet holds one row per PIN code of the Department of Posts'
# All India Pincode Directory (Open Government Data Platform India, under the
# Government Open Data License - India), with its districts and states.
import unicodedata
import numpy as np
import pandas as pd
notes = pd.read_csv("delivery_notes.csv", dtype="str")
directory = pd.read_parquet("pin_directory.parquet")
first_digits = "".join(sorted(directory["pin"].str[0].unique()))
print(f"directory: {len(directory):,} PIN codes, first digits {first_digits}")
def ascii_digits(text: str) -> str:
return "".join(
str(unicodedata.decimal(ch)) if ch.isdecimal() and not ch.isascii() else ch
for ch in text
)
text = notes["note"].map(ascii_digits)
text = text.str.replace(r"\b([0-9]{3}) ([0-9]{3})\b", r"\1\2", regex=True)
pin = text.str.extract(r"\b([0-9]{6})\b", expand=False)
well_formed = pin.str.fullmatch(r"[1-9][0-9]{5}") # missing PINs give False
known = pin.isin(directory["pin"])
checked = notes[["id"]].assign(
pin=pin,
status=np.select(
[pin.isna(), ~well_formed, ~known],
["no PIN found", "not a valid PIN", "not in the directory"],
default="ok",
),
).merge(directory[["pin", "district"]], on="pin", how="left")
print(checked.to_string(index=False, na_rep="-"))
print()
print(checked["status"].value_counts().to_string()) Output
directory: 19,586 PIN codes, first digits 123456789 id pin status district D01 411038 ok Pune D02 580020 ok Dharwad D03 122016 ok Gurugram D04 793001 ok East Khasi Hills D05 110024 ok South / South East D06 - no PIN found - D07 - no PIN found - D08 221005 ok Varanasi D09 560001 ok Bengaluru Urban D10 600400 not in the directory - D11 000000 not a valid PIN - D12 834001 ok Ranchi status ok 8 no PIN found 2 not in the directory 1 not a valid PIN 1
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 check_pins.py
- The structure check uses
str.fullmatch, which must match the whole value rather than a part of it.[1-9][0-9]{5}rejects a leading zero, and the directory agrees: every one of its 19,586 PIN codes starts with a digit from 1 to 9. D11’s placeholder000000fails here. - The existence check is a plain
isinagainst the directory. D10’s600400has the right shape but is absent from this snapshot.600040is the plausible Anna Nagar candidate in the copy, but only the customer can confirm the intended value. np.selectturns the checks into one readable status per row, and the merge adds the district, so a person can compare it with the town in the note. D02 says Hubballi, which lies in Dharwad district.- The final count, 8 of 12 notes ok against this snapshot, is the headline of this run, and every other row carries a reason someone can act on. A known PIN does not establish that it belongs to the customer’s intended address or that the snapshot reflects every current postal change.
Checkpoint
Check: Shape and directory membership
Choose text or pattern explicitly for each method
A regex treats some characters as instructions: . matches one character other than a newline by default,
+ repeats the preceding item, and ( opens a group. That makes
it easy to search for a pattern when you meant a piece of text. Product codes with a dot in them show the trap, in all
three engines this track uses:
Compare all four product codes under a pattern and literal text. Then compare each replacement method’s separate default.
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- Read four codes. OIL-2.5L, OIL-235L, OIL-2X5L and GHEE-2-5KG each contain 2 followed by one character and 5.
- Use a pattern. contains with a pattern reports all four, because the dot consumes one character other than a newline by default.
- Use literal text. An explicit literal search reports only OIL-2.5L. pandas and Polars use different names for the literal switch.
- Choose replacement. A replacement has its own defaults. The recorded run turns OIL-2.5L into OIL-2_5L for pandas' literal replacement, but _IL-2.5L for Polars' first regex match.
# Searching product codes for the text "2.5": which functions read the dot as
# "any character"?
import duckdb
import pandas as pd
import polars as pl
codes = ["OIL-2.5L", "OIL-235L", "OIL-2X5L", "GHEE-2-5KG"]
s = pd.Series(codes)
lf = pl.DataFrame({"code": codes})
code = pl.col("code")
con = duckdb.connect()
duck = con.sql(
"SELECT contains(code, '2.5') AS c, regexp_matches(code, '2.5') AS r FROM lf"
).pl()
rows = {
"pandas contains": s.str.contains("2.5"),
"pandas regex=False": s.str.contains("2.5", regex=False),
"polars contains": lf.select(code.str.contains("2.5")).to_series(),
"polars literal=True": lf.select(code.str.contains("2.5", literal=True)).to_series(),
"duckdb contains": duck["c"],
"duckdb regexp_matches": duck["r"],
}
print(" " * 22 + "".join(f"{c:>11}" for c in codes))
for name, hits in rows.items():
print(f"{name:22}" + "".join(f"{'match' if h else '-':>11}" for h in hits))
def one(sql):
return con.sql(sql).fetchone()[0]
replaced = {
"pandas str.replace": s.str.replace(".", "_")[0],
"polars str.replace": lf.select(code.str.replace(".", "_")).item(0, 0),
"duckdb replace": one("SELECT replace('OIL-2.5L', '.', '_')"),
"duckdb regexp_replace": one("SELECT regexp_replace('OIL-2.5L', '.', '_')"),
}
print()
print("Replacing '.' with '_' in OIL-2.5L:")
for name, value in replaced.items():
print(f"{name:22}{value}") Output
OIL-2.5L OIL-235L OIL-2X5L GHEE-2-5KG pandas contains match match match match pandas regex=False match - - - polars contains match match match match polars literal=True match - - - duckdb contains match - - - duckdb regexp_matches match match match match Replacing '.' with '_' in OIL-2.5L: pandas str.replace OIL-2_5L polars str.replace _IL-2.5L duckdb replace OIL-2_5L duckdb regexp_replace _IL-2.5L
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 literal_or_regex.py
pandas’ str.contains reads "2.5" as “a 2, any one character, a 5”, so it also matches 235, 2X5 and 2-5;
regex=False searches for the text itself. polars’ str.contains behaves the same way, and literal=True switches the
pattern off. DuckDB went the other way: its contains() searches for text, and regexp_matches() is the pattern
version. The replace functions disagree as well. pandas’ str.replace has read its pattern as plain text by default
since pandas 2.0, while polars’ str.replace reads a pattern and replaces only the first match, which here is the
first character, so OIL-2.5L became _IL-2.5L.
| Criterion | pandas | polars | DuckDB |
|---|---|---|---|
| Does it contain …? | str.contains: a pattern (regex=False for text) | str.contains: a pattern (literal=True for text) | contains(): text; regexp_matches(): a pattern |
| Replace | str.replace: text (regex=True for a pattern), every match | str.replace: a pattern, first match only; str.replace_all: every match | replace(): text, every match; regexp_replace(): a pattern, first match unless the g option |
| Extract | str.extract and str.extractall: always a pattern | str.extract and str.extract_all: a pattern | regexp_extract(): a pattern, an empty string when nothing matches |
| Count matches | str.count: a pattern | str.count_matches: a pattern (literal=True for text) | len(regexp_extract_all()): a pattern |
| Starts with … | str.startswith: text | str.starts_with: text | starts_with(): text |
When the text you search for comes from a user or a file, pass the text switch, or escape the string with
re.escape so that every special character stands for itself.
Checkpoint
Check: Literal text and pattern defaults
One column can use different regex engines
pandas, polars and DuckDB do not share a regex engine, and the differences reach patterns that look harmless. pandas
runs str.extract, str.extractall and str.findall with Python’s re. With PyArrow installed, as in this track’s
setup, its str dtype passes str.contains, str.match, str.fullmatch, str.count and regex
str.replace to PyArrow’s compute functions, which are built on the RE2 library. It falls back to re for calls
that PyArrow cannot handle, for example when the call passes flags or the pattern holds a lookaround or a
backreference, as pandas’ own source code shows. polars uses Rust’s regex crate, and DuckDB uses RE2.
Follow Varanasi’s Devanagari candidate through extraction and containment. Inspect the recorded errors before transferring the pattern to another engine.
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- Read Varanasi. Varanasi's candidate uses Devanagari decimal digits. A digit class and a boundary rule are separate parts of its definition.
- Python extraction. The pinned pandas extract call uses Python re and returns those digits. Polars' Unicode digit class returns them too.
- Arrow containment. The pinned Arrow-backed contains call and DuckDB's RE2 extraction do not recognize them with backslash-d. Explicit ASCII classes narrow just the digit choice.
- Check other syntax. Lookarounds are another difference: the recorded lookbehind succeeds in pandas extraction and is rejected by Polars and DuckDB.
# One pattern, four regex engines: Python's re, RE2 inside PyArrow and DuckDB,
# and Rust's regex crate in polars.
import duckdb
import pandas as pd
import polars as pl
notes = ["Pune 411038", "Varanasi २२१००५", "Hyderabad"]
s = pd.Series(notes) # pandas 3 "str" dtype, stored by PyArrow
df = pl.DataFrame({"note": notes})
note = pl.col("note")
con = duckdb.connect()
def show(label, values):
print(f"{label:28}{[None if pd.isna(v) else v for v in values]}")
def duck(pattern):
rows = con.execute("SELECT regexp_extract(note, ?, 1) FROM df", [pattern]).fetchall()
return [value for (value,) in rows]
print(r"Does \d match the Devanagari digits २२१००५?")
show("pandas str.contains", s.str.contains(r"\d{6}"))
show("pandas str.extract", s.str.extract(r"(\d{6})", expand=False))
show("polars str.extract", df.select(note.str.extract(r"(\d{6})", 1)).to_series())
show("duckdb regexp_extract", duck(r"(\d{6})"))
show("[0-9]{6}, pandas extract", s.str.extract(r"([0-9]{6})", expand=False))
behind = r"((?<=Pune )[0-9]{6})"
print()
print("A lookbehind, (?<=Pune )[0-9]{6}:")
show("pandas str.extract", s.str.extract(behind, expand=False))
for name, run in [
("polars str.extract", lambda: df.select(note.str.extract(behind, 1))),
("duckdb regexp_extract", lambda: duck(behind)),
]:
try:
run()
except Exception as error:
print(f"{name:28}{type(error).__name__}")
print()
print("Python's ASCII flag (?a) in pandas str.contains:")
try:
s.str.contains(r"(?a)\d{6}")
except Exception as error:
print(f"{'':28}{type(error).__name__}: {str(error).split(': ', 1)[1]}") Output
Does \d match the Devanagari digits २२१००५?
pandas str.contains [True, False, False]
pandas str.extract ['411038', '२२१००५', None]
polars str.extract ['411038', '२२१००५', None]
duckdb regexp_extract ['411038', '', '']
[0-9]{6}, pandas extract ['411038', None, None]
A lookbehind, (?<=Pune )[0-9]{6}:
pandas str.extract ['411038', None, None]
polars str.extract ComputeError
duckdb regexp_extract InvalidInputException
Python's ASCII flag (?a) in pandas str.contains:
ArrowInvalid: invalid perl operator: (?a
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 engines.py
\dmeans any decimal digit in Python’sreand in Rust’s regex crate, but only 0 to 9 in RE2. So on the same pandas column,str.contains(r"\d{6}")said no to Varanasi’s Devanagari PIN code, whilestr.extractwith the same pattern returned it.[0-9]means the same ten digits in every engine.- RE2 and Rust’s regex crate reject lookarounds and backreferences under their documented pattern contracts.
These features are outside the engines’ supported syntax. polars raised
ComputeErrorand DuckDBInvalidInputExceptionfor the lookbehind that pandas accepted. Put a group around the part you want instead:Pune ([0-9]{6}). - DuckDB’s
regexp_extractreturns an empty string where pandas and polars return a missing value, so a count of missing values in DuckDB stays at zero unless you writeNULLIF(regexp_extract(...), ''). - Python’s inline flag
(?a), which makes\dmean 0 to 9 inre, is not RE2 syntax. pandas passed the pattern to PyArrow, which rejected it withArrowInvalid.
Checkpoint
Check: Engine and boundary differences
Test accepted values and near misses together
A pattern is a small program, and it deserves tests. Write down the values it must accept and the values it must reject, near misses above all, and run the pattern over them before it meets a million rows. The script below tests a pattern for each of three formats, plus a naive first attempt at the mobile number:
Compare the six declared mobile cases with the naive ten-digit rule. Count its three mistakes before applying the normalized full-string rule.
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- State the examples. The six examples contain plain, international and trunk-prefixed forms, plus a wrong first digit, a short number and a landline.
- Try ten digits. The naive ten-digit test gets three wrong: it rejects two accepted prefixed forms and accepts 5123456789.
- Normalize separators. Removing permitted spaces and hyphens makes the form's accepted prefixes explicit. This does not establish that a number is assigned.
- Require the full value. The full-string rule agrees with all six declared expected results and returns 9845012345 from the normalized international example.
The mobile number and IFSC rules used here
Within India a mobile number is dialled as ten digits; from a fixed line a 0 goes in front, and callers from abroad
use India’s country code, +91, as TRAI’s consultation paper on the National Numbering Plan and the ITU’s list of
country codes set out. The exercise’s accepted mobile shapes start with 6, 7, 8 or 9. The cited TRAI consultation describes numbering
resources and a plan, accepted
by the Department of Telecommunications, to give fixed-line area codes that start with 6, 3, 4 and 2 to mobile
numbers once the current ranges run out, so these first-digit limits are this form’s declared rule, rather than a permanent
numbering guarantee. A shape check does not establish that a number has been assigned. An IFSC (Indian Financial System Code) identifies a bank branch for NEFT transfers: 11 characters, of which
the first four letters stand for the bank, the fifth is always 0 and the last six stand for the branch, according
to the Reserve Bank of India’s FAQ on NEFT. That gives the pattern [A-Z]{4}0[A-Z0-9]{6}.
# A pattern is tested on values it must accept and values it must reject
# before it meets real data.
import re
PIN = re.compile(r"[1-9][0-9]{5}")
MOBILE_NAIVE = re.compile(r"[0-9]{10}")
MOBILE = re.compile(r"(?:\+91|91|0)?([6-9][0-9]{9})")
IFSC = re.compile(r"[A-Z]{4}0[A-Z0-9]{6}")
def tidy_phone(text: str) -> str:
return re.sub(r"[\s-]", "", text) # spaces and hyphens are only for reading
def ascii_identifier(text: str) -> str:
return text.upper() if text.isascii() else ""
PIN_CASES = {"411038": True, "900099": True, "011038": False, "41103": False,
"4110380": False, "४११०३८": False}
MOBILE_CASES = {"9845012345": True, "+91 98450 12345": True, "098450-12345": True,
"5123456789": False, "984501234": False, "044 2626 1234": False}
IFSC_CASES = {"SBIN0000691": True, "hdfc0001234": True, "ICIC0ABC123": True,
"HDFCO001234": False, "SBIN000691": False, "SBIN1000691": False,
"ssbi0ABC123": True, "ßBI0ABC123": False, "ffBI0ABC123": False}
CASES = {
"PIN code": (PIN.fullmatch, str, PIN_CASES),
"mobile, naive": (MOBILE_NAIVE.fullmatch, tidy_phone, MOBILE_CASES),
"mobile": (MOBILE.fullmatch, tidy_phone, MOBILE_CASES),
"IFSC": (IFSC.fullmatch, ascii_identifier, IFSC_CASES),
}
for name, (test, prepare, cases) in CASES.items():
wrong = [text for text, expected in cases.items()
if bool(test(prepare(text))) != expected]
verdict = "all agree" if not wrong else f"wrong on {', '.join(wrong)}"
print(f"{name:14} {len(cases)} examples: {verdict}")
print()
print("normalised mobile:", MOBILE.fullmatch(tidy_phone("+91 98450-12345")).group(1)) Output
PIN code 6 examples: all agree mobile, naive 6 examples: wrong on +91 98450 12345, 098450-12345, 5123456789 mobile 6 examples: all agree IFSC 9 examples: all agree normalised mobile: 9845012345
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 pattern_tests.py
The naive mobile pattern, ten digits and nothing else, got half of its examples wrong: it rejected two accepted example shapes
written with +91 or a leading 0, and it accepted 5123456789. The final pattern removes spaces and hyphens first,
allows the prefixes and captures the ten-digit number, which is the form worth storing. Keep each test table next to
its pattern, so that the next change to the pattern meets the same near misses. The IFSC table also rejects
ßBI0ABC123 and ffBI0ABC123: uppercasing would expand their non-ASCII letters into an ASCII-looking value.
Require an original ASCII token before changing letter case, while retaining lowercase ASCII spellings.
Checkpoint
Check: Accept and reject examples
Practise extracting three contact fields
Customers who paid on delivery typed their contact details for a refund into one text column. Write
extract_contacts(df) so that it returns a PIN code, a mobile number and an IFSC for each of the ten contacts, with a
missing value wherever a field is absent or not valid. The docstring of the starting point states the rules.
id,contact
C01,"Asha Rao, 98450 12345, Indiranagar, Bengaluru 560038, refund to HDFC0001234"
C02,"Imran S. | +91-91234-56789 | Andheri East, Mumbai 400053 | IFSC icic0006543"
C03,"R. Iyer, landline 044 2626 1234, Anna Nagar, Chennai 600040, SBIN0001234"
C04,"Neha, 9876543210, Gomti Nagar, Lucknow 226010, IFSC HDFCO002345"
C05,"Karan Mehta 0 98765 43210, Sector 62, Noida 201309, UTIB0000123"
C06,"Fatima, 5123456789, Salt Lake, Kolkata, PIN 000000, PUNB0123400"
C07,"Joseph, +91 99887 76655, Ernakulam 682 011, KKBK0000958"
C08,"Priya S, 98451-23456, Jayanagar, Bengaluru 560011, ifsc canr0001234"
C09,"Sunil, 99887 76650 or 99887 76651, Jaipur 302017, no IFSC yet"
C10,"Meera, +91 87654 32109, Coimbatore 641018, HDFC0001234 (old: HDFC0000999)" # Your starting point: fill in pin, mobile and ifsc for every contact.
import pandas as pd
def extract_contacts(df: pd.DataFrame) -> pd.DataFrame:
"""Return the columns id, pin, mobile and ifsc, one row per contact.
A field that is absent or not valid is a missing value.
pin six digits with no digit next to them, the first 1-9;
"682 011" counts as 682011
mobile ten digits starting with 6, 7, 8 or 9, with or without +91, 91
or 0 in front, spaces and hyphens allowed; keep only the ten
digits, from the first valid number of a contact
ifsc four letters, the digit 0, then six letters or digits, in any
case; return it in capitals
"""
out = df[["id"]].copy()
# Write your code here.
return out The sample checks compare your three columns with the expected values, row by row. With the starting point, one of the six checks passes.
# Sample checks for extract_contacts.py. Run `python check_contacts.py` in the
# folder that holds all three files.
import pandas as pd
from extract_contacts import extract_contacts
contacts = pd.read_csv("contacts.csv", dtype="str")
before = contacts.copy()
EXPECTED = {
"pin": ["560038", "400053", "600040", "226010", "201309",
None, "682011", "560011", "302017", "641018"],
"mobile": ["9845012345", "9123456789", None, "9876543210", "9876543210",
None, "9988776655", "9845123456", "9988776650", "8765432109"],
"ifsc": ["HDFC0001234", "ICIC0006543", "SBIN0001234", None, "UTIB0000123",
"PUNB0123400", "KKBK0000958", "CANR0001234", None, "HDFC0001234"],
}
result = extract_contacts(contacts)
checks = []
def check(name, test):
try:
problem = test()
except Exception as error: # a missing column or a wrong type fails the check
problem = f"{type(error).__name__}: {error}"
checks.append(problem is None)
label = "ok " if problem is None else "FAIL"
print(label, name + ("" if problem is None else f": {problem}"))
def columns():
want = ["id", "pin", "mobile", "ifsc"]
if list(result.columns) != want or len(result) != len(contacts):
return (f"expected the columns {want} and {len(contacts)} rows, "
f"got {list(result.columns)} and {len(result)} rows")
return None
def values(column):
def test():
got = [None if pd.isna(v) else v for v in result[column]]
pairs = zip(contacts["id"], EXPECTED[column], got)
wrong = [f"{i} expected {e}, got {g}" for i, e, g in pairs if e != g]
if not wrong:
return None
more = f" (and {len(wrong) - 2} more)" if len(wrong) > 2 else ""
return "; ".join(wrong[:2]) + more
return test
def real_missing():
empty = [c for c in ["pin", "mobile", "ifsc"] if (result[c] == "").any()]
return None if not empty else f"empty strings in {empty}: use a missing value instead"
def unchanged():
if contacts.equals(before):
return None
return "extract_contacts changed the DataFrame it was given"
check("columns and rows", columns)
for column in ["pin", "mobile", "ifsc"]:
check(f"{column} values", values(column))
check("missing values are missing", real_missing)
check("input left unchanged", unchanged)
print(f"{sum(checks)} of {len(checks)} checks pass") Output
FAIL columns and rows: expected the columns ['id', 'pin', 'mobile', 'ifsc'] and 10 rows, got ['id'] and 10 rows FAIL pin values: KeyError: 'pin' FAIL mobile values: KeyError: 'mobile' FAIL ifsc values: KeyError: 'ifsc' FAIL missing values are missing: KeyError: 'pin' ok input left unchanged 1 of 6 checks pass
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 check_contacts.py
Put the three files in a folder of their own and edit only extract_contacts.py. You are done when
python check_contacts.py reports 6 of 6 checks pass. The pandas worksheet keeps its DataFrame return, column order and source index. The additional public suite below
checks its nullable inputs, repeated indexes, text dtypes and immutability as well as these ten contacts.
import pandas as pd
from extract_contacts import extract_contacts
CONTACTS = [
"Asha Rao, 98450 12345, Indiranagar, Bengaluru 560038, refund to HDFC0001234",
"Imran S. | +91-91234-56789 | Andheri East, Mumbai 400053 | IFSC icic0006543",
"R. Iyer, landline 044 2626 1234, Anna Nagar, Chennai 600040, SBIN0001234",
"Neha, 9876543210, Gomti Nagar, Lucknow 226010, IFSC HDFCO002345",
"Karan Mehta 0 98765 43210, Sector 62, Noida 201309, UTIB0000123",
"Fatima, 5123456789, Salt Lake, Kolkata, PIN 000000, PUNB0123400",
"Joseph, +91 99887 76655, Ernakulam 682 011, KKBK0000958",
"Priya S, 98451-23456, Jayanagar, Bengaluru 560011, ifsc canr0001234",
"Sunil, 99887 76650 or 99887 76651, Jaipur 302017, no IFSC yet",
"Meera, +91 87654 32109, Coimbatore 641018, HDFC0001234 (old: HDFC0000999)",
]
def frame(notes, index=None):
return pd.DataFrame({"id": [f"C{i + 1:02d}" for i in range(len(notes))], "contact": notes}, index=index)
def values(result, name):
return [None if pd.isna(value) else value for value in result[name]]
def test_all_original_contacts():
result = extract_contacts(frame(CONTACTS))
assert values(result, "pin") == [
"560038", "400053", "600040", "226010", "201309",
None, "682011", "560011", "302017", "641018",
]
assert values(result, "mobile") == [
"9845012345", "9123456789", None, "9876543210", "9876543210",
None, "9988776655", "9845123456", "9988776650", "8765432109",
]
assert values(result, "ifsc") == [
"HDFC0001234", "ICIC0006543", "SBIN0001234", None, "UTIB0000123",
"PUNB0123400", "KKBK0000958", "CANR0001234", None, "HDFC0001234",
]
def test_exact_columns_order_and_repeated_index():
given = frame(CONTACTS[:3], index=["same", "same", "other"])
result = extract_contacts(given)
assert list(result.columns) == ["id", "pin", "mobile", "ifsc"]
assert result.index.tolist() == ["same", "same", "other"]
assert result["id"].tolist() == given["id"].tolist()
assert values(result, "pin") == ["560038", "400053", "600040"]
def test_input_is_not_changed():
given = frame(CONTACTS)
before = given.copy(deep=True)
extract_contacts(given)
pd.testing.assert_frame_equal(given, before)
def test_long_and_formatted_numbers_are_not_sliced():
result = extract_contacts(frame([
"Call 984 501 2345; PIN 560038",
"Call 98450123456; PIN 5600380",
"Landline 044 2626 1234; PIN 600040",
]))
assert values(result, "pin") == ["560038", None, "600040"]
assert values(result, "mobile") == ["9845012345", None, None]
def test_first_valid_candidates_and_prefixes():
result = extract_contacts(frame([
"000000 or 560038; 5123456789 or +91 98450 12345; HDFCO001234 or ICIC0ABC123",
"PIN 682 011; 91-99887-76655 or 9845012345; sbin0001234 or HDFC0001234",
"PIN 226010; 0 98765 43210",
]))
assert values(result, "pin") == ["560038", "682011", "226010"]
assert values(result, "mobile") == ["9845012345", "9988776655", "9876543210"]
assert values(result, "ifsc") == ["ICIC0ABC123", "SBIN0001234", None]
def test_ifsc_is_a_whole_token_and_o_is_not_zero():
result = extract_contacts(frame([
"XHDFC0001234", "HDFC00012345", "HDFCO001234", "ICIC0ABC123",
]))
assert values(result, "ifsc") == [None, None, None, "ICIC0ABC123"]
def test_unicode_decimal_digits_and_real_missing_values():
result = extract_contacts(frame(["PIN ६८२ ०११; +९१ ९९८८७ ७६६५५; kkbk0000958", None, ""]))
assert values(result, "pin") == ["682011", None, None]
assert values(result, "mobile") == ["9988776655", None, None]
assert values(result, "ifsc") == ["KKBK0000958", None, None]
assert not result[["pin", "mobile", "ifsc"]].eq("").any().any()
def test_ifsc_original_ascii_without_unicode_case_expansion():
result = extract_contacts(frame([
"ßBI0ABC123", "ffBI0ABC123", "sSbi0abc123",
"PIN ६८२ ०११; +९१ ९९८८७ ७६६५५; kkbk0000958",
"HDFC०००१२३४",
]))
assert values(result, "ifsc") == [None, None, "SSBI0ABC123", "KKBK0000958", None]
assert values(result, "pin")[3] == "682011"
assert values(result, "mobile")[3] == "9988776655"
def test_empty_input_has_the_declared_columns():
result = extract_contacts(frame([]))
assert list(result.columns) == ["id", "pin", "mobile", "ifsc"]
assert len(result) == 0
def test_nullable_contacts_multiindex_and_text_dtypes():
index = pd.MultiIndex.from_tuples([("a", 1), ("a", 1), ("b", 2)], names=["group", "row"])
given = pd.DataFrame({"id": ["a", "a", "b"], "contact": [None, pd.NA, "PIN 682011"]}, index=index)
given["contact"] = given["contact"].astype("string")
before = given.copy(deep=True)
result = extract_contacts(given)
assert result.index.equals(index)
assert result.index.names == ["group", "row"]
assert values(result, "pin") == [None, None, "682011"]
assert all(str(result[name].dtype) == "str" for name in ["pin", "mobile", "ifsc"])
pd.testing.assert_frame_equal(given, before)
def test_empty_and_missing_columns_still_hold_text():
for given in [frame([]), frame([None])]:
result = extract_contacts(given)
assert all(str(result[name].dtype) == "str" for name in ["pin", "mobile", "ifsc"]) First hint for the pandas worksheet: a mobile number may contain spaces and hyphens, so collect candidates with
str.extractall, using a pattern such as \+?[0-9][0-9 -]{8,}[0-9]. Tidy each whole candidate and keep the first
one that passes fullmatch; do not take a PIN slice from a longer number. Keep the original text for the IFSC:
select a whole alphanumeric token, require original ASCII, then uppercase that token and test its full shape.
Apply the declared Unicode decimal-digit conversion to a separate PIN/mobile search copy.
The supplemental exercise below uses standard Python record lists for the same field rules. It keeps repeated ids and returns one record per contact; it does not implement the DataFrame interface. Its prompt and first hint describe the record-list input and output.
Exercise · Medium · Python
Extract three fields without cutting a longer number
This supplemental exercise uses standard Python records to practise the field rules. Implement extract_contacts(rows) for a list of dictionaries with id and contact. Return a list of dictionaries with keys id, pin, mobile, ifsc, in that order, preserving the input order and repeated ids. Leave the input unchanged. A missing contact is None.
Convert Unicode decimal digits to ASCII digits before testing PIN and mobile candidates. A numeric chunk contains digits with optional spaces or hyphens between them, and may start with +. Consider the whole chunk: a six-digit slice of a longer phone number is not a PIN.
- A PIN candidate is a chunk without
+whose spaces and hyphens can be removed to leave exactly six digits, starting with 1–9. - A mobile candidate leaves ten digits starting with 6–9 after removing spaces, hyphens and an optional
+91,91or0prefix. Keep the ten digits. - An IFSC candidate is an original whole ASCII alphanumeric token of four letters,
0, then six letters or digits. Return capitals for ASCII lowercase letters. Do not correctOinto zero or expand non-ASCII letters into ASCII spellings.
Keep the first valid candidate for each field. Return a real missing value for an absent field, including a missing contact. These are the form's accepted shapes; they do not prove that a phone is assigned or an IFSC belongs to a current branch.
The sample tests include all ten contacts from the lesson, repeated ids, longer near misses, two candidates, Unicode digits and empty input. The separate pandas worksheet has the DataFrame and index contract; this record exercise does not implement that library interface.
Starter code · extract_contacts.py
def extract_contacts(rows):
"""Return id, pin, mobile and ifsc records, without changing the input."""
return [{"id": row["id"]} for row in rows] The sample tests · test_extract_contacts.py
from copy import deepcopy
from extract_contacts import extract_contacts
CONTACTS = [
"Asha Rao, 98450 12345, Indiranagar, Bengaluru 560038, refund to HDFC0001234",
"Imran S. | +91-91234-56789 | Andheri East, Mumbai 400053 | IFSC icic0006543",
"R. Iyer, landline 044 2626 1234, Anna Nagar, Chennai 600040, SBIN0001234",
"Neha, 9876543210, Gomti Nagar, Lucknow 226010, IFSC HDFCO002345",
"Karan Mehta 0 98765 43210, Sector 62, Noida 201309, UTIB0000123",
"Fatima, 5123456789, Salt Lake, Kolkata, PIN 000000, PUNB0123400",
"Joseph, +91 99887 76655, Ernakulam 682 011, KKBK0000958",
"Priya S, 98451-23456, Jayanagar, Bengaluru 560011, ifsc canr0001234",
"Sunil, 99887 76650 or 99887 76651, Jaipur 302017, no IFSC yet",
"Meera, +91 87654 32109, Coimbatore 641018, HDFC0001234 (old: HDFC0000999)",
]
def frame(notes, index=None):
return [{"id": index[i] if index is not None else f"C{i + 1:02d}", "contact": note}
for i, note in enumerate(notes)]
def values(result, name):
return [row[name] for row in result]
def test_all_original_contacts():
result = extract_contacts(frame(CONTACTS))
assert values(result, "pin") == [
"560038", "400053", "600040", "226010", "201309",
None, "682011", "560011", "302017", "641018",
]
assert values(result, "mobile") == [
"9845012345", "9123456789", None, "9876543210", "9876543210",
None, "9988776655", "9845123456", "9988776650", "8765432109",
]
assert values(result, "ifsc") == [
"HDFC0001234", "ICIC0006543", "SBIN0001234", None, "UTIB0000123",
"PUNB0123400", "KKBK0000958", "CANR0001234", None, "HDFC0001234",
]
def test_exact_keys_row_order_and_repeated_ids():
given = frame(CONTACTS[:3], index=["same", "same", "other"])
result = extract_contacts(given)
assert all(list(row) == ["id", "pin", "mobile", "ifsc"] for row in result)
assert [row["id"] for row in result] == ["same", "same", "other"]
assert [row["id"] for row in result] == [row["id"] for row in given]
assert values(result, "pin") == ["560038", "400053", "600040"]
def test_input_is_not_changed():
given = frame(CONTACTS)
before = deepcopy(given)
extract_contacts(given)
assert given == before
def test_long_and_formatted_numbers_are_not_sliced():
result = extract_contacts(frame([
"Call 984 501 2345; PIN 560038",
"Call 98450123456; PIN 5600380",
"Landline 044 2626 1234; PIN 600040",
]))
assert values(result, "pin") == ["560038", None, "600040"]
assert values(result, "mobile") == ["9845012345", None, None]
def test_first_valid_candidates_and_prefixes():
result = extract_contacts(frame([
"000000 or 560038; 5123456789 or +91 98450 12345; HDFCO001234 or ICIC0ABC123",
"PIN 682 011; 91-99887-76655 or 9845012345; sbin0001234 or HDFC0001234",
"PIN 226010; 0 98765 43210",
]))
assert values(result, "pin") == ["560038", "682011", "226010"]
assert values(result, "mobile") == ["9845012345", "9988776655", "9876543210"]
assert values(result, "ifsc") == ["ICIC0ABC123", "SBIN0001234", None]
def test_ifsc_is_a_whole_token_and_o_is_not_zero():
result = extract_contacts(frame([
"XHDFC0001234", "HDFC00012345", "HDFCO001234", "ICIC0ABC123",
]))
assert values(result, "ifsc") == [None, None, None, "ICIC0ABC123"]
def test_unicode_decimal_digits_and_real_missing_values():
result = extract_contacts(frame(["PIN ६८२ ०११; +९१ ९९८८७ ७६६५५; kkbk0000958", None, ""]))
assert values(result, "pin") == ["682011", None, None]
assert values(result, "mobile") == ["9988776655", None, None]
assert values(result, "ifsc") == ["KKBK0000958", None, None]
assert all(row[column] != "" for row in result for column in ["pin", "mobile", "ifsc"])
def test_ifsc_original_ascii_without_unicode_case_expansion():
result = extract_contacts(frame([
"ßBI0ABC123", "ffBI0ABC123", "sSbi0abc123",
"PIN ६८२ ०११; +९१ ९९८८७ ७६६५५; kkbk0000958",
"HDFC०००१२३४",
]))
assert values(result, "ifsc") == [None, None, "SSBI0ABC123", "KKBK0000958", None]
assert values(result, "pin")[3] == "682011"
assert values(result, "mobile")[3] == "9988776655"
def test_empty_input_has_no_records():
result = extract_contacts(frame([]))
assert result == [] A hint
Separate finding candidates from accepting one. Inspect whole numeric chunks, normalize their separators, and use full-string tests for their lengths and prefixes. Scan original ASCII alphanumeric tokens for the IFSC. Build one output record per input position so repeated ids do not collapse rows.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.
Practice that adapts to you
Practise this lesson
15 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
Fresher · What is the difference between str.extract and str.extractall in pandas?
str.extract applies a pattern with at least one capture group to each row and keeps only the first match: one result
row per input row, one column per group, columns named after (?P<name>…) groups, and a missing value where a row
does not match. str.extractall keeps every match: one result row per match, with the original index plus a level
called match that numbers the matches of each row from 0, and rows without a match are left out. Use str.extract
when a row should hold one value, such as the PIN code of an address, and str.extractall when it may hold several,
such as every phone number in a note. Then count the matches per row, so that rows with two candidates receive an explicit selection decision
instead of quietly reduced to the first.
Fresher · Why does df[“code”].str.contains(“2.5”) match OIL-235L, and how do you search for the text itself?
str.contains treats its argument as a regular expression by default (regex=True), and in a regular expression a dot
matches one character other than a newline by default, so 2.5 also matches 235, 2X5 and 2-5. To search for the text itself, pass
regex=False, or escape the dot as r"2\.5"; for a whole string that comes from a user, re.escape escapes every
special character. polars has the same default, which literal=True switches off, while DuckDB’s contains() searches
for plain text and regexp_matches() is its pattern version. pandas’ str.replace went the other way and reads plain
text by default, so check the default of each method rather than assuming one rule for all of them.
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Fresher to mid
You extracted PIN codes from 2 million typed delivery addresses, and 7 % of the rows came back without one. How do you decide what to repair automatically, what to send back, and what to report?
-
Mid to senior
A phone-number regex gives one count in your pandas notebook, a smaller count in the DuckDB pipeline, and an error in polars. Walk through what you check and how you make the three agree.
Key takeaways
str.extractreturns the first match of each capture group as columns, named after(?P<name>…)groups, with a missing value where a row does not match;str.extractallreturns every match, with amatchindex level.- Put word boundaries around codes:
\b[0-9]{6}\bkeeps a PIN-code pattern out of phone numbers. - Write
[0-9]when you mean the digits 0 to 9.\dalso matches other scripts’ digits in Python’sreand in polars, but not in RE2, which pandas 3 uses forstr.containswhen PyArrow is installed. - List and classify the rows that fail; automate only the repairs that need no guess, and report how many rows each repair changed.
- Check the structure with
str.fullmatch, then the existence against a reference list, and give every row a status. str.containsreads a pattern by default in pandas and polars, DuckDB’scontains()reads text, and pandas’str.replacereads text; test every pattern on values it must accept and near misses it must reject.
Terms in this lesson
- capture group
- A parenthesized part of a regular expression whose matched text can be returned separately from the rest of the match.
- regular expression
- A pattern language for matching text. The selected engine and method define its character classes, boundaries and returned matches.
- word boundary
- A position between a word and a nonword character, or between a word character and an input edge. The engine defines what counts as a word character.
Corrections
- Clarified boundaries, controlled repairs, snapshot membership and original ASCII IFSC tokens, retaining the delivery-note examples and corrected explanations.
- Clarified the IFSC hint: keep original ASCII tokens before case changes, and distinguish the pandas worksheet hint from the record-list exercise.
References
- Working with text data (pandas user guide) (pandas development team (NumFOCUS))
- pandas.Series.str.extract (pandas API reference) (pandas development team (NumFOCUS))
- pandas.Series.str.extractall (pandas API reference) (pandas development team (NumFOCUS))
- pandas.Series.str.contains (pandas API reference) (pandas development team (NumFOCUS))
- PyArrow functionality (pandas user guide) (pandas development team (NumFOCUS))
- pandas 3.0.6 source: the PyArrow-backed string array (string_arrow.py) (pandas development team (NumFOCUS))
- re: Regular expression operations (The Python Standard Library) (Python Software Foundation)
- Strings (Polars user guide) (Polars)
- regex crate: syntax and limitations (The Rust Project Developers (regex crate))
- Regular Expressions (DuckDB documentation) (DuckDB Foundation)
- Text Functions (DuckDB documentation) (DuckDB Foundation)
- RE2 regular expression syntax (RE2 project)
- Compute functions (Apache Arrow C++ documentation) (The Apache Software Foundation)
- Postal addressing systems in member countries: India (Universal Postal Union)
- All India Pincode Directory (Open Government Data Platform India) (Department of Posts, Government of India)
- Government Open Data License – India (Open Government Data Platform India)
- Consultation Paper on Revision of National Numbering Plan (Telecom Regulatory Authority of India)
- List of ITU-T Recommendation E.164 assigned country codes (International Telecommunication Union)
- Frequently Asked Questions on NEFT (IFSC) (Reserve Bank of India)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress