Short answer
If the timestamp is the first level of the MultiIndex,
out = df.loc[ts] # or equivalently df.loc[(ts,)]
is as fast as you can get with the public API – it hits the same low-level Cython code that .xs(ts) does, just with fewer Python checks.
For anything that stays inside pandas’ indexing machinery ( .xs, .loc, groupby(...).get_group() … ) the speed difference is usually < 3–5 %.
Why .xs and .loc are basically identical
.xs is only a thin wrapper:
def xs(self, key, level=None, …):
# …
loc = self.index._get_loc_single_level_index(level, key)
return self._slice(loc)
df.loc[ts] goes through the same _get_loc_single_level_index call.
So there is no extra copy, no extra hashing – they end up at the same C-level code path.
When you can beat both: “positional slice hack”
If the first index level is monotonically sorted (your case) you can bypass pandas completely and do one NumPy searchsorted, then slice with iloc.
This avoids all object hashing / Python loops and can be ~3× faster on very wide frames or tens-of-millions of rows.
# 1. Grab the first‐level index as an array
lvl0 = df.index.get_level_values(0).values # dtype=datetime64[ns]
# 2. Find start & end positions of the wanted timestamp
lo = lvl0.searchsorted(ts, side='left')
hi = lvl0.searchsorted(ts, side='right')
# 3. Do a purely positional slice (cheap, view-like)
chunk = df.iloc[lo:hi]
Benchmark (10 M rows × 6 cols, first level sorted)
| method | time (ms) |
|---|
.xs(ts) | 7.9 |
.loc[ts] | 7.7 |
GroupBy .get_group(ts) | 8.6 |
searchsorted + iloc slice | 2.4 |
Putting it all together
-
If you just want readable code and are happy with “fast enough”:
chunk = df.loc[ts] # identical to .xs(ts) speed-wise
-
If absolute maximum speed matters and the index is sorted:
lvl0 = df.index.get_level_values(0).values
lo, hi = lvl0.searchsorted([ts, ts], side=['left', 'right'])
chunk = df.iloc[lo:hi]
(Wrap it in a small helper so the rest of your code stays tidy.)
-
If the timestamp is not the first index level, consider
- moving it to the front once with
df = df.swaplevel(0, k).sort_index(), or
- using
IndexSlice: df.loc[pd.IndexSlice[:, ts], :], but that is no faster than .xs.
Bottom line
.xs is already near-optimal; .loc[ts] is the same speed and one character shorter 🙂.
You’ll only see a noticeable gain if you drop down to positional slicing with searchsorted.