pythonintermediate

Pandas merge_asof for Time-Based Joins

Perform an as-of join to match events to the most recent reference record within a time window.

python
import pandas as pd

prices = pd.DataFrame({'ts': pd.to_datetime(['09:00','09:05','09:10','09:20']), 'price':[100,101,102,103]})
trades = pd.DataFrame({'ts': pd.to_datetime(['09:02','09:08','09:15']), 'qty':[10,20,5]})

result = pd.merge_asof(trades.sort_values('ts'), prices.sort_values('ts'), on='ts')
print(result)

Use Cases

  • tick data joins
  • event-reference matching
  • time-series alignment

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.