Sub topic 7
Vectorised strings and dates with .str and .dt
This chapter assumes you can build a DataFrame, select columns, and write a basic loop in Python. It also assumes you have read the earlier chapters on column arithmetic and boolean masks. Here you replace per-row string and date handling with the .str and .dt accessors.
What the accessors are
An accessor is an attribute on a Series that groups related methods under one name. Two of them matter here:
Series.strholds string methods such asstrip,lower,containsandreplace. It works on columns of text.Series.dtholds date and time methods such asyear,month,day_nameandnormalize. It works on columns with a datetime dtype.
A row loop that cleans text or pulls a month out of a date does the same work for every row. The accessors let you write that work once and apply it to the whole column.
import pandas as pd
events = pd.DataFrame({
"name": [" Ann ", "bob", None, "CARL smith"],
"when": ["2026-01-05", "2026-02-10", "not a date", "2026-03-15"],
})
events["name_clean"] = events["name"].str.strip().str.title()
events["when_dt"] = pd.to_datetime(
events["when"], format="%Y-%m-%d", errors="coerce"
)
events["month"] = events["when_dt"].dt.month
print(events[["name_clean", "when_dt", "month"]])Three things happen in this example:
.str.strip().str.title()chains two string operations. Each one returns a new Series.- The missing name (
None) becomesNaNand stays missing. A loop would need anifcheck to avoid an error onNone. errors="coerce"turns the unparseable"not a date"intoNaT, which is the missing-value marker for datetimes..dt.monththen returnsNaNfor that row, so themonthcolumn has dtypefloat64instead of an integer.
How much faster is it really?
The two accessors do not give the same kind of speedup.
- The
.dtaccessor works ondatetime64data, which is stored as a compact numeric array. Operations like.dt.monthrun in compiled code, so they are fast. - The
.straccessor on an ordinary object-dtype column still calls a Python string method once per value inside pandas. It skips the row-object overhead ofiterrowsand handles missing values for you, but it is not as fast as column arithmetic. Expect a modest gain over a plain Python loop. The gain overiterrowsis large.
Measure with timeit and check that the results match, as in the earlier chapter on measuring speed. Do not assume a fixed multiplier.
import timeit
import pandas as pd
names = pd.Series([" Ann ", "bob", "CARL smith"] * 10_000)
def with_loop(series):
out = []
for value in series:
out.append(value.strip().title())
return pd.Series(out, index=series.index)
def with_accessor(series):
return series.str.strip().str.title()
assert with_loop(names).tolist() == with_accessor(names).tolist()
print(timeit.timeit(lambda: with_loop(names), number=20))
print(timeit.timeit(lambda: with_accessor(names), number=20))This version has no missing values, so the plain loop is safe. Once the data may contain None or NaN, the loop needs an extra check on every value and the accessor does not.
Common .str methods
| Task | Method | Notes |
|---|---|---|
| Trim whitespace | `s.str.strip()` | Also `lstrip` and `rstrip`. |
| Change case | `s.str.lower()`, `.upper()`, `.title()` | |
| Length | `s.str.len()` | Returns a number per row. |
| Test for text | `s.str.contains("x")` | Returns a boolean Series. Treats the pattern as a regex by default. |
| Prefix or suffix | `s.str.startswith("x")`, `.endswith("x")` | Literal text, no regex. |
| Replace | `s.str.replace("a", "b", regex=False)` | Pass `regex=True` for patterns. |
| Split | `s.str.split(",", expand=True)` | `expand=True` returns a DataFrame with one column per piece. |
| Capture parts | `s.str.extract(r"(\d+)")` | Returns a DataFrame with one column per capture group. |
Filtering with str.contains
str.contains returns a boolean mask, so it plugs straight into the mask patterns from the earlier chapter. The default behaviour on missing values is a trap. A missing value produces NaN in the mask, and indexing with a mask that contains NaN raises an error. Pass na=False so missing rows count as "no match".
import pandas as pd
contacts = pd.DataFrame({
"email": ["[email protected]", "[email protected]", None, "[email protected]"],
})
mask = contacts["email"].str.contains("@example.com", na=False, regex=False)
print(contacts[mask])The call sets regex=False because . in a regex matches any character. For a literal search, turning regex off is both safer and a little faster.
Extracting fields with a regex
Per-row loops that slice or parse text often become one str.extract call. Named groups become column names.
import pandas as pd
log = pd.DataFrame({
"line": ["user=ann id=17", "user=bob id=204", "malformed"],
})
parts = log["line"].str.extract(r"user=(?P<user>\w+) id=(?P<id>\d+)")
log = log.join(parts)
log["id"] = pd.to_numeric(log["id"])
print(log)Rows that do not match the pattern get NaN in every extracted column. The extracted values are strings, so convert numbers with pd.to_numeric. The join works because extract keeps the original index.
Dates: parse once, then use .dt
The .dt accessor only works on a column whose dtype is datetime. A column of date strings has object dtype, and calling .dt on it raises AttributeError: Can only use .dt accessor with datetimelike values. The fix is to convert first with pd.to_datetime.
Parsing text is the expensive step, so do it once and keep the datetime column. Give an explicit format when you know it. That is faster than letting pandas guess, and it avoids guesses that silently swap day and month on ambiguous dates such as 03/04/2026.
Date parts and differences
Subtracting two datetime columns gives a timedelta column. The .dt accessor works on timedeltas too.
import pandas as pd
orders = pd.DataFrame({
"placed": pd.to_datetime(
["2026-01-05 14:30", "2026-01-06 09:15", "2026-01-10 23:50"]
),
"shipped": pd.to_datetime(
["2026-01-07 10:00", "2026-01-06 18:00", "2026-01-12 08:00"]
),
})
orders["days_to_ship"] = (orders["shipped"] - orders["placed"]).dt.days
orders["weekday"] = orders["placed"].dt.day_name()
orders["placed_day"] = orders["placed"].dt.normalize()
orders["is_weekend"] = orders["placed"].dt.dayofweek >= 5
print(orders)The new columns work like this:
.dt.dayson a timedelta returns the whole-day part only, so 1 day 19 hours gives1. Use.dt.total_seconds() / 86400when you need fractional days..dt.normalize()sets the time of day to midnight and keeps the datetime dtype. This is useful for grouping by calendar day..dt.dayofweekcounts Monday as 0 and Sunday as 6. The comparison>= 5is an ordinary vectorised boolean expression, so it can feednumpy.whereor a mask.
Other useful members include .dt.year, .dt.quarter, .dt.hour, .dt.floor("h"), and .dt.to_period("M") for month buckets.
Edge cases and common errors
- Missing values propagate. A string method on
NoneorNaNreturnsNaN. A date method onNaTreturnsNaN. This is usually what you want, but count missing values withisna().sum()before and after a cleanup so you notice rows that were lost. - Regex is on by default for some methods.
str.containstreats its pattern as a regex.str.replacedoes not in current pandas (it defaults toregex=False), but older versions did. Stateregex=explicitly so the code means the same thing in any version. - Assignment aligns on the index. A result from
.stror.dtkeeps the index of its source Series. Assigning it back to a DataFrame matches rows by index label, as described in the earlier chapter on alignment. If you filtered or reindexed in between, check that the indexes still agree. - Time zones. A datetime column can be naive or time-zone aware. Mixing the two in a subtraction raises
TypeError. Use.dt.tz_localize("UTC")to attach a zone to a naive column and.dt.tz_convert(...)to change zones. - Unparseable dates. Without
errors="coerce",pd.to_datetimeraises on the first bad value. With it, bad values becomeNaT. Usedf[df["when_dt"].isna()]to find the rows that failed to parse and decide whether to fix or drop them.
Choosing between accessor, mask and loop
The final branch is a fallback. Custom parsing that depends on several columns at once, or on state from earlier rows, may genuinely need apply or itertuples. The last chapters cover what those cost.
Summary
.strand.dtreplace per-row text and date code with one call per column..dtis truly vectorised on datetime data..strmainly removes row-object overhead and handles missing values.- Convert date strings with
pd.to_datetimeonce, usingformat=anderrors="coerce", before calling.dt. - Use
na=Falsewithstr.containswhen you build masks, and setregex=explicitly. - Verify a rewrite against the loop result and time both, as in the earlier chapter.
Exercise
A DataFrame df has a column signup of strings such as "2026-03-14" (some are malformed) and a column email of strings (some are missing). Write code that creates a boolean column recent_example that is True only when the email ends with "@example.com" and the signup date falls in March 2026 or later. Missing or unparseable values must give False, not an error.
Show answer
df["signupdt"] = pd.todatetime(df["signup"], format="%Y-%m-%d", errors="coerce") df["recentexample"] = ( df["email"].str.endswith("@example.com", na=False) & (df["signupdt"] >= "2026-03-01") ) Parsing with errors="coerce" turns malformed dates into NaT, and comparing NaT with a date gives False. Using na=False in endswith turns missing emails into False. The & operator combines the two boolean Series row by row, so no loop is needed.