Question Details

No question body available.

Tags

python pandas dataframe merge ffill

Answers (1)

Accepted Answer Available
Accepted Answer
February 5, 2026 Score: 4 Rep: 267,303 Quality: Expert Completeness: 80%

You can use a simple mergeasof on time:

merge = pd.mergeasof(truth, pred, on='time')

NB. mergeasof requires keys in both inputs to be sorted, and it doesn't maintain the original index (like all merges).

Output:

   time  truth  pred
0   0.0      0   NaN
1  10.0      0   NaN
2  20.0      0   NaN
3  30.0      0   3.0
4  40.0      0   3.0
5  50.0      0   2.0
6  60.0      0   2.0
7  70.0      0   1.0
8  80.0      0   1.0
9  90.0      0   1.0

By default, it picks the previous or equal available right key, for the next one use direction='forward':

pd.mergeasof(truth, pred, on='time', direction='forward')

time truth pred 0 0.0 0 3.0 1 10.0 0 3.0 2 20.0 0 3.0 3 30.0 0 2.0 4 40.0 0 2.0 5 50.0 0 1.0 6 60.0 0 1.0 7 70.0 0 1.0 8 80.0 0 NaN 9 90.0 0 NaN

And handle exact matches with allow
exactmatches=False:

pd.mergeasof(truth, pred, on='time', allowexactmatches=False)

time truth pred 0 0.0 0 NaN 1 10.0 0 NaN 2 20.0 0 NaN 3 30.0 0 3.0 4 40.0 0 3.0 5 50.0 0 2.0 6 60.0 0 2.0 7 70.0 0 2.0 # picked the previous time 8 80.0 0 1.0 9 90.0 0 1.0