Pandas date range selection: Slicing a datetime index with .loc

Pandas date range selection: Slicing a datetime index with .loc

Want to select a chunk of time from a Python Pandas data frame?

Make the datetime column the index, then use .loc and a slice to choose dates:

(
  df
  .set_index('tpep_pickup_datetime')
  .sort_index()
  .loc['2025-11-10':'2025-11-20']
  ['trip_distance']
  .mean()
)