Sub topic 12
String and datetime namespaces
This chapter assumes you can already write pandas .str and .dt code and that you know Polars expressions from the earlier chapters. It covers the Polars equivalents and the places where behavior differs.
Namespaces are expression methods
In pandas, .str and .dt are accessors on a Series. In Polars they are namespaces on an expression: pl.col("name").str... and pl.col("ts").dt.... The methods return expressions, so you use them inside select, with_columns, filter or agg. Nulls pass through: a string method on a null returns null.
import polars as pl
df = pl.DataFrame({
"name": [" Alice Smith ", "bob jones", None],
"ordered_at": ["2024-01-15 09:30:00", "2024-02-03 17:45:00", "2024-02-20 08:00:00"],
})
out = (
df.with_columns(
pl.col("name").str.strip_chars().str.to_titlecase().alias("clean_name"),
pl.col("ordered_at").str.to_datetime("%Y-%m-%d %H:%M:%S").alias("ts"),
)
.with_columns(
pl.col("ts").dt.year().alias("year"),
pl.col("ts").dt.month().alias("month"),
pl.col("ts").dt.weekday().alias("weekday"),
pl.col("ts").dt.truncate("1mo").alias("month_start"),
)
)
print(out)The second with_columns is a separate step because expressions in one context cannot see columns created in that same context.
Common translations
| pandas | Polars |
|---|---|
| `s.str.strip()` | `pl.col("s").str.strip_chars()` |
| `s.str.lower()` | `pl.col("s").str.to_lowercase()` |
| `s.str.len()` | `pl.col("s").str.len_chars()` |
| `s.str.replace(p, r, regex=True)` | `pl.col("s").str.replace_all(p, r)` |
| `pd.to_datetime(s, format=f)` | `pl.col("s").str.to_datetime(f)` |
| `s.dt.dayofweek` | `pl.col("s").dt.weekday()` |
| `s.dt.to_period("M")` | `pl.col("s").dt.truncate("1mo")` |
| `s.dt.strftime(f)` | `pl.col("s").dt.strftime(f)` |
Differences that cause bugs
- Regex by default.
str.containsandstr.replace_alltreat the pattern as a regex. Passliteral=Truefor plain text. pandas 2.x defaults toregex=Falseinreplace, so ported code can change behavior silently. - Replace once or all.
str.replacechanges only the first match.str.replace_allchanges every match. pandasreplacechanges all matches. - Weekday numbering. pandas
dayofweekruns 0 (Monday) to 6 (Sunday). Polarsdt.weekday()runs 1 (Monday) to 7 (Sunday). - Length.
len_charscounts characters andlen_bytescounts bytes. Uselen_charsto match pandas. - Null in filters. A comparison on a null gives null, and
filterdrops those rows.str.containson a null name therefore removes that row:
matches = out.filter(pl.col("clean_name").str.contains("(?i)smith"))
print(matches)- Parsing is strict.
str.to_datetimeraises an error on values that do not match the format. Passstrict=Falseto get null for bad values, which is closer toerrors="coerce"in pandas.
Time-based grouping
dt.truncate replaces most uses of resample and to_period. It rounds each timestamp down to the start of its bucket, and then you use an ordinary group_by. For irregular or rolling windows, use group_by_dynamic. Polars has no period dtype, so month buckets are datetimes at the start of the month.
Exercise
A pandas script filters with df["code"].str.contains("a.b") and expects to match only the literal text "a.b". After porting to pl.col("code").str.contains("a.b"), it also matches "axb". What is the fix, and why did the pandas script behave differently?
Show answer
Use pl.col("code").str.contains("a.b", literal=True). The . is a regex wildcard. Polars treats the pattern as a regex by default. The pandas script did not hit this because it was written for or ran with a setting where the pattern was literal, such as regex=False. In pandas, contains defaults to regex=True, so check what the original call actually set.