Sub topic 6
Indexing and slicing with a DatetimeIndex
This chapter assumes you can create pandas Series and DataFrames, select with .loc, and convert text with pd.to_datetime. Here you will see how a datetime index changes selection.
Why a DatetimeIndex
A DatetimeIndex is an index whose labels are datetime64 timestamps. With one, .loc accepts date strings and treats them as spans of time, not as exact labels. You can write "2024-03" and get the whole month.
Make the index from a column with set_index. Sort it afterward.
import pandas as pd
df = pd.DataFrame({
"when": pd.to_datetime(
["2024-03-05 08:00", "2024-03-01 09:30", "2024-03-02 14:45"],
format="%Y-%m-%d %H:%M",
),
"amount": [40, 10, 25],
})
ts = df.set_index("when")["amount"].sort_index()
print(ts.index)The printed index shows dtype='datetime64[ns]' (newer pandas versions may show a different unit) and the three timestamps in order.
Partial string indexing
A string shorter than the index's full precision selects every row inside that period.
print(ts.loc["2024-03-02"])
print(ts.loc["2024-03-01":"2024-03-04"])The first call returns the one row from March 2 (25 at 14:45). The second returns the rows from March 1 and March 2.
The string's precision decides what you get back:
| String | Meaning | Result type |
|---|---|---|
| `"2024"` | All of 2024 | Series or DataFrame |
| `"2024-03"` | All of March 2024 | Series or DataFrame |
| `"2024-03-02"` | All of March 2 | Series or DataFrame |
| `"2024-03-02 14:45"` | That exact minute, when the index resolution is also minutes | A single value |
Slicing by range
Slices on a datetime index include both endpoints. A partial string as the end point extends to the end of that period, so "2024-03-04" includes every moment on March 4.
The endpoints do not need to exist in the index. This works only if the index is sorted. On an unsorted index, a slice with a missing endpoint raises a KeyError. That is why the example calls sort_index().
print(ts.loc["2024-03-02":])
print(ts.loc[:"2024-03-01"])
print(ts.loc["2024-03"].sum())Open-ended slices work as in ordinary Python. The last line sums all March values.
DataFrames and boolean masks
On a DataFrame, use .loc for row selection by date string. Plain df["2024-03-02"] is not the supported way to select rows.
frame = ts.to_frame()
print(frame.loc["2024-03-01":"2024-03-02", "amount"])
print(frame[frame.index.month == 3].shape)You can also build masks from index attributes such as frame.index.month or frame.index.dayofweek. Use a mask when the condition is not a contiguous range, such as "all Mondays".
Common errors
KeyErroron a slice. The index is unsorted and an endpoint is missing. Callsort_index().- A scalar where you expected a Series. Your string was as precise as the index. Use a shorter string or a slice like
ts.loc["2024-03-02":"2024-03-02"]. - Strings that parse the wrong way.
"03/04/2024"can mean March 4 or April 3. Use ISO format (YYYY-MM-DD) in selections. - Time zone mismatches. On a time-zone-aware index, strings are read in the index's own zone. Comparing with timestamps from another zone needs conversion first.
Exercise
Given ts above, which expression returns all rows from March 2 and later, and why does it still work if no row has the exact time 00:00 on March 2?
Show answer
ts.loc["2024-03-02":]. A partial string starts at the beginning of that period, so no exact label is needed. The index is sorted, so pandas can find the position of the start point.