DataFrame basics I · Topic 8 Free
Regular expressions: rlike()
Same tasks, other language: the SQL version of this topic.
Data model — the tables you will query
How the tables join
| Relationship | Cardinality | Join condition |
|---|---|---|
| students.cohort_id → cohorts.id | many students → one cohort | JOIN cohorts ON students.cohort_id = cohorts.id |
| enrollments.student_id → students.id | many enrollments → one student | JOIN students ON enrollments.student_id = students.id |
| enrollments.course_id → courses.id | many enrollments → one course | JOIN courses ON enrollments.course_id = courses.id |
| job_offers.student_id → students.id | many job offers → one student | JOIN students ON job_offers.student_id = students.id |
In short: each student belongs to one cohort. Students enroll in courses through enrollments, and their job offers land in job_offers.
SQL’s regex operator ~ becomes the Column method .rlike() (“regex like”).
SELECT name FROM students WHERE name ~ '^[AM]';
students.filter(col("name").rlike("^[AM]")).select("name")
The same regex syntax
Everything you learned in the SQL regex topic carries over unchanged:
| Pattern | Matches |
|---|---|
. | any single character |
^ / $ | start / end of the string |
[abc], [a-z], [0-9] | character sets and ranges |
+ / * / ? | one or more / zero or more / optional |
(ab|cd) | ab or cd |
courses.filter(col("title").rlike("[0-9]")) # contains a digit
job_offers.filter(col("role").rlike("(Analyst|Engineer)")) # either word
students.filter(col("name").rlike("^A.*a$")) # starts A, ends a
Like in SQL, an unanchored regex matches anywhere in the string — use ^ and $ to pin it down.
Cleaning data with regex
The matching operator’s best friend is the replacement function — a data engineering workhorse:
students.select(F.regexp_replace(col("name"), "[aeiou]", "*").alias("masked"))
You will use regexp_replace for stripping currency signs, fixing phone formats, and normalizing messy text in almost every pipeline.
When to use what
- Exact value →
== - Starts with / contains / ends with →
like(),startswith(),contains() - Anything more complex →
rlike()
Practice
Real Python runs in your browser with the PySpark DataFrame API. Solve the tasks, or just experiment.