pandas / Advanced: ownership, windows and analytical acceptance / Lesson 21
Point-in-Time As-of Joins
Join observations to prior values while enforcing availability time, ordering, and freshness constraints.
On this page
Lesson goals
- Explain backward as-of matching and sorted keys.
- Bound staleness with an explicit tolerance.
- Prevent future information and cross-entity matches.
- Specify entity, availability, direction, exact-match and tolerance rules for as-of joins.
- Verify matched source identity, age and coverage without future leakage.
Define the point-in-time question
An as-of join matches a row to a nearby key rather than requiring equality. For a historical prediction, the relevant value is generally one available no later than the prediction time, not a later correction. Define the entity, availability timestamp, direction, exact-match policy, and maximum permitted age before joining.
A source event timestamp can differ from the time its value became available. Joining on the former alone can leak information that was not yet known. Preserve both timestamps when possible and design the join around the actual decision boundary.
Match earlier values
In a local pandas lab, the example joins sorted numeric time keys with backward direction. Each event finds the latest right-hand key at or before it. The values are synthetic and the public reader does not execute the code. Real data may additionally require entity grouping and timestamp normalization.
import pandas as pd
events = pd.DataFrame({"time": [2, 5, 9]})
values = pd.DataFrame({"time": [1, 4, 8], "value": [10, 20, 30]})
print(pd.merge_asof(events, values, on="time", direction="backward"))
Events 2, 5, and 9 match prior keys 1, 4, and 8 respectively.
Reject stale matches
A match can be temporally earlier yet too old to be useful. Set a tolerance appropriate to the key type and business contract, and count unmatched rows after the join. In this fixture no right-hand key exactly equals an event key, so a zero tolerance leaves the values unmatched.
import pandas as pd
events = pd.DataFrame({"time": [2, 5, 9]})
values = pd.DataFrame({"time": [1, 4, 8], "value": [10, 20, 30]})
print(pd.merge_asof(events, values, on="time", direction="backward", tolerance=0))
All three matches are missing because each candidate is one unit earlier and exceeds the zero tolerance.
Respect entities and ordering
Sort the as-of key as required by the installed pandas version and use appropriate grouping keys when values belong to different entities. Test two entities with interleaved timestamps and an exact-boundary case. Inspect matched source times as well as values; otherwise a plausible number can conceal a cross-entity or future match.
Verify the join contract
Reconcile input and output counts, unmatched rates, match ages, and representative records at the tolerance boundary. Confirm that no matched availability time is later than the prediction time for a backward contract. Document how duplicate right-hand timestamps and late corrections are handled, and test those rules with source owners before using the features.
Define what was available at the decision time
An as-of join selects a nearby ordered key rather than requiring equality. For a causal historical feature, the central question is which value was actually available for the same entity at or before the decision time. An event’s effective time and the time its value was published or ingested can differ. A correction describing an earlier event but published later must not enter an earlier prediction merely because its event time is old. Preserve both timestamps and choose the availability field that matches the information contract.
State the left row grain, right record grain, entity key, time unit or timezone, direction, exact-match policy, maximum age and handling of missing matches. A backward match is often appropriate for historical availability; forward or nearest can select future information and must be justified by the task. The join does not decide whether a value is authoritative, whether a correction was available, or whether the chosen source covers every expected entity.
Prepare ordered and compatible keys
pandas.merge_asof requires both inputs sorted by the as-of key in ascending order. With interleaved entities, sort by the time key globally as required by the API; sorting by entity first can leave the overall time key nonmonotonic. Use by or explicit left_by/right_by for entity equality so a nearby record from another entity cannot match. Validate nonmissing keys, compatible numeric or datetimelike types and timezone interpretation before joining. Keep a stable left event ID and a right source ID for audit.
The right-hand time key may be named differently from the left decision time. Use left_on and right_on to preserve both, then inspect matched availability time and value. For every backward match assert right_time <= decision_time and calculate age as decision_time minus right_time. A plausible value alone cannot reveal a future, cross-entity or stale match. Null as-of keys are not a substitute for a missing-match policy; reject or quarantine them before the operation and reconcile excluded identities.
Specify direction, exactness and tolerance
direction="backward" selects the last right key less than or equal to the left key by default. direction="forward" selects a later candidate, while nearest chooses the closest key and can therefore be future information. allow_exact_matches=False excludes an equal key when the contract requires information strictly before the decision. A matching tolerance bounds distance in the units of the key; for datetime keys use a compatible Timedelta. An older candidate outside the tolerance remains unmatched, and an observation exactly at an allowed boundary should be tested explicitly.
Duplicate right records at the same entity and time require an authority rule before the join. The operation’s ordering behavior can select one of them, but it cannot decide which conflicting payload is correct. Resolve versions or ties using a documented source priority and availability policy, or quarantine the conflict. Do not let incidental input order become a business rule. Similarly, a value can be temporally prior but invalid or unavailable for another reason; validate source quality and reporting eligibility separately.
Trace a synthetic availability join
The program below matches three synthetic decisions to published values for entities A and B. A decision at time 5 uses A’s value available at time 4; B at time 6 uses B’s value at time 5; A at time 9 uses A’s value at time 8. Both inputs are sorted globally by their numeric time keys, and by="entity" prevents cross-entity matches. A tolerance of two time units admits all three matches. The result retains each right availability time so the assertion can check no matched value comes from the future.
If A’s time-8 value were published at time 10, it would not be available for the time-9 decision even if it described an earlier event. The right key must represent the appropriate availability time for the prediction contract. Check source identity, entity, age, output row count and unmatched IDs after the join; keeping the left row count alone does not establish correct matches. The example uses synthetic numeric times and no external service.
import pandas as pd
decisions = pd.DataFrame({'id':['A5','B6','A9'], 'entity':['A','B','A'], 'decision':[5,6,9]}).sort_values('decision')
values = pd.DataFrame({'entity':['A','B','A'], 'available':[4,5,8], 'value':[10,20,30]}).sort_values('available')
r = pd.merge_asof(decisions, values, left_on='decision', right_on='available', by='entity', direction='backward', tolerance=2)
assert r['id'].tolist() == ['A5','B6','A9']
assert (r['available'] <= r['decision']).all()
assert r['value'].tolist() == [10,20,30]
print(r['value'].tolist(), (r['decision']-r['available']).tolist())
[10, 20, 30] [1, 1, 1]
Each decision matches its own entity’s prior available value at age one. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Verify coverage and temporal evidence
An acceptance fixture should include two interleaved entities, an exact match, a candidate exactly at tolerance, an older candidate just outside tolerance, a missing prior value, a late correction and duplicate right times. For matched records, compare the actual source IDs, entity, availability time, age and value with independently derived expectations. For unmatched records, report the left IDs and reasons rather than replacing missing values with apparently fresh defaults. Reconcile left input and output identities and counts, and verify the intended ordering of the final report.
Timezone-aware timestamps must represent compatible instants before comparison; document source timezone and daylight-saving policy rather than treating naive local clocks as UTC by convenience. A fixed tolerance expresses elapsed distance, which may differ from a business-calendar rule. The selected teaching baseline is pandas 3.1.0; official merge_asof and merge references consulted during authoring identified themselves as 3.1.1. Standalone examples are separately qualified on isolated synthetic inputs with exact Python, pandas and NumPy versions. They do not certify production data availability or model performance. These standalone programs were executed in that isolated environment.
20 worked examples
1. Reuse a prior source record
Problem: Match two decisions to one still-eligible prior source record.
- Both decisions at 5 and 8 can use the record available at 4.
- Their ages are 1 and 4, both within tolerance 4; the source row is not consumed.
import pandas as pd
l = pd.DataFrame({'id':['D5','D8'], 'decision':[5,8]})
r = pd.DataFrame({'available':[4], 'source':['R4'], 'v':[20]})
j = pd.merge_asof(l,r,left_on='decision',right_on='available',direction='backward',tolerance=4)
print(j['source'].tolist(), (j['decision']-j['available']).tolist())
['R4', 'R4'] [1, 4]
Both decisions retain source ID R4 with separately checked ages. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: An as-of join can reuse one eligible right record for multiple left decisions.
2. Forward candidate
Problem: Find the next value at or after a reference time.
- The first right key at or after 5 is 6.
- That candidate carries value 30.
import pandas as pd
l = pd.DataFrame({'t':[5]})
r = pd.DataFrame({'t':[2,4,6], 'v':[10,20,30]})
print(pd.merge_asof(l,r,on='t',direction='forward')['v'].tolist())
[30]
Forward matching can use future information relative to the left time. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Forward matching can use future information relative to the left time.
3. Nearest candidate
Problem: Choose the numerically closest right key to a left time.
- Key 1 is four units from time 5.
- Key 7 is two units away and is selected.
import pandas as pd
l = pd.DataFrame({'t':[5]})
r = pd.DataFrame({'t':[1,7], 'v':[10,30]})
print(pd.merge_asof(l,r,on='t',direction='nearest')['v'].tolist())
[30]
Nearest matching is not inherently causal because the closest value may be later. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Nearest matching is not inherently causal because the closest value may be later.
4. Allow exact match
Problem: Match a right key equal to the decision time.
- The right key 5 equals the left key.
- The explicit exact-match policy permits value 30.
import pandas as pd
l = pd.DataFrame({'t':[5]})
r = pd.DataFrame({'t':[4,5], 'v':[20,30]})
print(pd.merge_asof(l,r,on='t',direction='backward',allow_exact_matches=True)['v'].tolist())
[30]
Exact-match policy defines whether same-time information is eligible. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Exact-match policy defines whether same-time information is eligible.
5. Exclude exact match
Problem: Select a strictly earlier key when an exact key exists.
- The right key 5 is excluded by the strict policy.
- The previous key 4 is the latest eligible candidate.
import pandas as pd
l = pd.DataFrame({'t':[5]})
r = pd.DataFrame({'t':[4,5], 'v':[20,30]})
print(pd.merge_asof(l,r,on='t',direction='backward',allow_exact_matches=False)['v'].tolist())
[20]
Disabling exact matches enforces a strictly prior key. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Disabling exact matches enforces a strictly prior key.
6. Tolerance boundary
Problem: Match a prior candidate exactly two units old with tolerance two.
- The distance from decision 5 to candidate 3 is two.
- That distance meets the tolerance of two in this fixture.
import pandas as pd
l = pd.DataFrame({'t':[5]})
r = pd.DataFrame({'t':[3], 'v':[20]})
print(pd.merge_asof(l,r,on='t',direction='backward',tolerance=2)['v'].tolist())
[20]
The exact allowed boundary is an essential tolerance test. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: The exact allowed boundary is an essential tolerance test.
7. Stale candidate
Problem: Reject a prior candidate beyond the allowed distance.
- The candidate at 2 is three units older than decision 5.
- That exceeds the tolerance of two, so the value is unmatched.
import pandas as pd
l = pd.DataFrame({'t':[5]})
r = pd.DataFrame({'t':[2], 'v':[20]})
j = pd.merge_asof(l,r,on='t',direction='backward',tolerance=2)
print(j['v'].isna().tolist())
[True]
A prior candidate can still be too stale for the contract. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: A prior candidate can still be too stale for the contract.
8. Entity grouping
Problem: Match a prior value only within the same entity.
- B has the closer time 4 but is a different entity.
- The latest eligible A value is at time 3 and equals 10.
import pandas as pd
l = pd.DataFrame({'entity':['A'], 't':[5]})
r = pd.DataFrame({'entity':['A','B'], 't':[3,4], 'v':[10,99]})
j = pd.merge_asof(l,r,on='t',by='entity',direction='backward')
print(j['v'].tolist())
[10]
The by key prevents a cross-entity match. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: The by key prevents a cross-entity match.
9. Unsorted as-of key
Problem: Catch an error from an unsorted left as-of key.
- The left times 5 then 2 are not ascending.
- merge_asof raises a ValueError for the unsorted key.
import pandas as pd
l = pd.DataFrame({'t':[5,2]})
r = pd.DataFrame({'t':[1,4], 'v':[10,20]})
try:
pd.merge_asof(l,r,on='t')
except ValueError:
print('unsorted left')
unsorted left
Sort by the as-of key before joining. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Sort by the as-of key before joining.
10. Availability versus event time
Problem: Reject a correction published after the decision.
- The record describes an event at 3 but is available only at 6.
- Decision time 5 precedes availability, so no backward match exists.
import pandas as pd
l = pd.DataFrame({'decision':[5]})
r = pd.DataFrame({'event':[3], 'available':[6], 'v':[20]})
j = pd.merge_asof(l,r,left_on='decision',right_on='available',direction='backward')
print(j['v'].isna().tolist())
[True]
Availability time prevents a late correction from leaking into the earlier decision. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Availability time prevents a late correction from leaking into the earlier decision.
11. Retain matched time
Problem: Inspect a matched availability time and its age.
- The matched value became available at time 6.
- Its age at decision 8 is 8-6=2.
import pandas as pd
l = pd.DataFrame({'decision':[8]})
r = pd.DataFrame({'available':[6], 'v':[20]})
j = pd.merge_asof(l,r,left_on='decision',right_on='available',direction='backward')
print(j.loc[0,'available'], j.loc[0,'decision']-j.loc[0,'available'])
6 2
Preserving the right key makes causal and staleness checks possible. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Preserving the right key makes causal and staleness checks possible.
12. No prior candidate
Problem: Identify an early decision with no earlier right key.
- The only right value appears at time 2.
- No candidate is at or before decision time 1.
import pandas as pd
l = pd.DataFrame({'t':[1]})
r = pd.DataFrame({'t':[2], 'v':[5]})
j = pd.merge_asof(l,r,on='t',direction='backward')
print(j['v'].isna().tolist())
[True]
A backward join retains the left row with a missing match. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: A backward join retains the left row with a missing match.
13. Duplicate right times
Problem: Inspect a backward match when two right rows share a key.
- Both right rows have the same time key 4.
- This backward operation selects the last eligible row in the supplied order.
import pandas as pd
l = pd.DataFrame({'t':[5]})
r = pd.DataFrame({'t':[4,4], 'v':[10,20]})
print(pd.merge_asof(l,r,on='t',direction='backward')['v'].tolist())
[20]
Incidental row order is not an authoritative conflict-resolution rule. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Incidental row order is not an authoritative conflict-resolution rule.
14. Missing time key
Problem: Identify a missing decision time before an as-of join.
- A has a known decision time.
- B lacks the required ordered key and must be handled separately.
import pandas as pd
l = pd.DataFrame({'id':['A','B'], 't':[1,None]})
print(l.loc[l['t'].isna(),'id'].tolist())
['B']
Pre-join validation prevents unknown times from entering the as-of operation. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Pre-join validation prevents unknown times from entering the as-of operation.
15. Timedelta tolerance
Problem: Match a timestamp candidate within a two-day tolerance.
- The candidate is exactly two elapsed days earlier.
- The compatible two-day tolerance permits the match.
import pandas as pd
l = pd.DataFrame({'t':pd.to_datetime(['2026-01-03T00:00Z'],utc=True)})
r = pd.DataFrame({'t':pd.to_datetime(['2026-01-01T00:00Z'],utc=True), 'v':[5]})
j = pd.merge_asof(l,r,on='t',direction='backward',tolerance=pd.Timedelta('2D'))
print(j['v'].tolist())
[5]
A datetime as-of tolerance uses a compatible duration. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: A datetime as-of tolerance uses a compatible duration.
16. Different time names
Problem: Join decision and availability columns with explicit names.
- The left decision key is 5 and the right availability key is 4.
- Both columns remain available to inspect the matched age.
import pandas as pd
l = pd.DataFrame({'decision':[5]})
r = pd.DataFrame({'available':[4], 'v':[20]})
j = pd.merge_asof(l,r,left_on='decision',right_on='available',direction='backward')
print(j.loc[0,'decision'], j.loc[0,'available'])
5 4
Explicit key names preserve evidence of the temporal relationship. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Explicit key names preserve evidence of the temporal relationship.
17. Interleaved entities
Problem: Join globally time-sorted records from two entities.
- The right keys are globally ordered 4 then 5.
- Entity A matches A at 5 and B matches B at 4.
import pandas as pd
l = pd.DataFrame({'entity':['A','B'], 't':[5,6]})
r = pd.DataFrame({'entity':['B','A'], 't':[4,5], 'v':[20,10]})
j = pd.merge_asof(l,r,on='t',by='entity',direction='backward')
print(j['v'].tolist())
[10, 20]
Global time order and entity grouping serve different requirements. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Global time order and entity grouping serve different requirements.
18. Left population
Problem: Count output rows when one left decision is unmatched.
- The time-1 decision has no earlier value.
- The time-5 decision matches time 4, and both left rows remain.
import pandas as pd
l = pd.DataFrame({'id':['A','B'], 't':[1,5]})
r = pd.DataFrame({'t':[4], 'v':[20]})
j = pd.merge_asof(l,r,on='t',direction='backward')
print(len(j), j['v'].isna().sum())
2 1
A left-style as-of result preserves rows but can contain unmatched values. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: A left-style as-of result preserves rows but can contain unmatched values.
19. Nearest tie
Problem: Inspect nearest selection for equally distant keys.
- Keys 4 and 6 are both one unit from time 5.
- The qualified runtime selects the earlier key 4 in this tie.
import pandas as pd
l = pd.DataFrame({'t':[5]})
r = pd.DataFrame({'t':[4,6], 'v':[10,20]})
print(pd.merge_asof(l,r,on='t',direction='nearest')['v'].tolist())
[10]
A tie fixture records actual selected-version behavior rather than an assumed policy. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: A tie fixture records actual selected-version behavior rather than an assumed policy.
20. Checked causal join
Problem: Check entity, age and output identity after a backward join.
- Each decision matches its own entity’s prior value.
- Both matched values are one time unit old and left identities remain.
import pandas as pd
l = pd.DataFrame({'id':['A5','B6'], 'entity':['A','B'], 'decision':[5,6]})
r = pd.DataFrame({'entity':['A','B'], 'available':[4,5], 'v':[10,20]})
j = pd.merge_asof(l,r,left_on='decision',right_on='available',by='entity',direction='backward',tolerance=2)
assert (j['available'] <= j['decision']).all()
print(j['id'].tolist(), (j['decision']-j['available']).tolist())
['A5', 'B6'] [1, 1]
Identity, entity and age checks support the stated causal contract. Qualified with Python 3.12.3, pandas 3.1.0 and NumPy 2.5.4 using synthetic inputs.
Why this result follows: Identity, entity and age checks support the stated causal contract.
Common errors and fixes
A historical feature uses a later correction.
- Why it happens
- The join used event time rather than availability time or allowed a forward match.
- How to fix it
- Join on the documented availability boundary and inspect matched times.
- Prevent it next time
- Include late-arrival fixtures in point-in-time tests.
A value from another entity appears in a row.
- Why it happens
- The entity grouping key was omitted.
- How to fix it
- Apply the appropriate grouping and verify source identifiers.
- Prevent it next time
- Test interleaved entities with distinctive values.
Old values are treated as current.
- Why it happens
- No maximum age was specified.
- How to fix it
- Set and validate a domain-appropriate tolerance.
- Prevent it next time
- Monitor unmatched rates and match ages.
20 practice exercises
1. An event occurs at time 5 and values exist at 4 and 6. Which matches a backward join?
Show hint
Choose the latest eligible key no later than the decision.
Show worked solution
Time 4 is the latest candidate at or before 5, assuming it is available and meets the tolerance and entity rules. Time 6 is future information.
Time 4 is the latest candidate at or before time 5; time 6 is future information. The match also requires the same entity, valid availability and an age within the stated tolerance.
Check your solution
- The backward candidate is time 4.
- Time 6 is excluded as future information.
2. A prior value is 20 days old but the contract allows seven days. What should happen?
Show hint
Compare candidate age with the maximum allowed age.
Show worked solution
The value should not match under a seven-day tolerance. Report the missing match and use the documented handling rather than silently treating it as fresh.
A value 20 days old exceeds a seven-day tolerance, so it remains unmatched. Record the decision identity and apply the documented missing-feature policy instead of treating the stale value as fresh.
Check your solution
- 20 days exceeds 7 days.
- The stale value is not accepted as a match.
3. Decision A occurs at 10; A values R2, R7 and R9 were available at 2, 7 and 9 respectively. Choose the backward match and retain its source ID.
Show hint
Select the latest eligible availability for the same entity.
Show worked solution
R9 is the latest value available at or before time 10, so it matches with age 1. Retain source ID R9 and availability time 9 to verify the choice; R2 and R7 are earlier eligible candidates but are not the latest.
Check your solution
- Matched source ID is R9 at time 9.
- The match age is 1.
4. A decision at 5 has a value at 6. Can a forward match be used in a feature available at time 5?
Show hint
A forward match is later than the decision.
Show worked solution
The forward join can select time 6, but that value is future information at time 5. Reject it for a strictly causal feature unless an independently documented availability contract shows it was known earlier; retain availability evidence.
Check your solution
- Forward candidate is time 6.
- It is later than the decision time.
5. A decision at 10 has prior value at 7 and future value at 11. Compare nearest and causal backward choices.
Show hint
The nearest candidate may be in the future.
Show worked solution
Nearest selects time 11 because it is one unit away, but a causal backward join selects time 7 because it was available by time 10. Apply the appropriate age tolerance to time 7 and report an unmatched result if it is too old.
Check your solution
- Nearest selects 11.
- Backward selects 7 before tolerance.
6. A decision at 5 has values at 4 and 5. Compare backward matching with exact matches allowed and forbidden.
Show hint
The strict policy excludes the equal key.
Show worked solution
With exact matches allowed, time 5 is selected. With allow_exact_matches=False, time 5 is excluded and the earlier time 4 becomes the match. State whether information arriving at the decision instant is considered available.
Check your solution
- Allowed exact match is 5.
- Strict prior match is 4.
7. A decision at 5 has only a right record at 5. What happens when exact matches are forbidden?
Show hint
There is no earlier candidate to fall back to.
Show worked solution
The equal key is excluded and no earlier record exists, so the left decision remains with a missing match. Report its identity and apply the documented no-prior policy rather than substituting the excluded value.
Check your solution
- The exact candidate is excluded.
- The resulting match is missing.
8. A decision at 10 has candidate times 7 and 6. With backward tolerance 3, which candidate qualifies and what is its age?
Show hint
Check the closest earlier key and the tolerance boundary.
Show worked solution
Time 7 is the latest earlier candidate and has age 3, exactly the allowed boundary, so it matches. Time 6 is four units old and would exceed the tolerance if it were the best candidate.
Check your solution
- Matched time is 7.
- Matched age equals tolerance 3.
9. Decisions at times 10 and 20 each have a latest prior value 4 units old. A tolerance of 3 applies. What should the report show?
Show hint
Compare each age with the maximum allowed.
Show worked solution
Both candidates exceed the tolerance and both left decisions remain unmatched. Report the two decision IDs and their stale-candidate ages separately if retained in diagnostics; do not silently treat either value as current.
Check your solution
- Both matches are missing.
- Each candidate age is 4, greater than 3.
10. A decision for entity A at time 10 sees A at 7 and B at 9. Which match is valid under backward entity-specific rules? An approved tolerance of 2 applies; determine whether the valid same-entity candidate actually matches.
Show hint
The nearest key must also belong to A.
Show worked solution
Before applying tolerance, the nearest same-entity backward candidate is A at 7, age 3; B at 9 is ineligible because it is a different entity. The approved tolerance of 2 rejects A’s age-3 candidate, so the final decision is unmatched.
Check your solution
- The same-entity candidate is A at time 7, age 3.
- The final result is unmatched because 3 exceeds tolerance 2.
11. Left rows sorted by entity are A@5,A@9,B@6. Why may merge_asof reject this order and how should it be repaired?
Show hint
The global as-of key sequence must be ascending.
Show worked solution
Times [5,9,6] are not globally ascending even though A’s rows are internally ordered. Sort by the as-of time to [5,6,9], retain the entity column for by matching and keep stable left IDs for restoring report order if needed.
Check your solution
- Original global time order is nonmonotonic.
- The repaired time order is [5,6,9].
12. A correction has event time 2 but becomes available at 8. A decision occurs at 5. May it be used? An earlier approved value was available at time 4 with value 7; determine the causal match.
Show hint
Compare availability time, not only event time.
Show worked solution
No. Although the event time is earlier, the correction was unavailable until time 8, after the decision. Join on the appropriate availability timestamp and preserve both timestamps for audit; the time-5 decision must not receive this correction. The time-5 decision uses the time-4 value 7, subject to tolerance; it must not use the correction available at 8.
Check your solution
- Event time 2 precedes the decision.
- Availability time 8 follows the decision and is ineligible.
- The eligible prior value is 7 at time 4.
13. Decision D at 12 matches source R available at 9. Design two post-join assertions for a backward tolerance of 3.
Show hint
Check both direction and age using retained right time.
Show worked solution
Assert the source entity matches D’s entity and 9<=12, then calculate age 12-9=3 and assert it is within tolerance. Retain D and R identifiers so a correct-looking value can be traced to the chosen source record.
Check your solution
- The matched time is not in the future.
- Age 3 meets the tolerance boundary.
14. Initially, decision D at time 2 has right records at 3 and 4 only. Determine the backward output. In a second scenario, add a same-entity prior fallback at time 0 and apply tolerance 2.
Show hint
No candidate exists at or before the decision.
Show worked solution
Initially D has no candidate at or before 2 and remains unmatched. In the second scenario, time 0 is exactly two units old and matches at the allowed tolerance boundary; the records at 3 and 4 remain future candidates.
Check your solution
- Initially D has no backward match.
- With the time-0 fallback, D matches it at age 2.
15. Two right rows for entity A are both available at 4, with conflicting values 10 and 20. Design a pre-join policy.
Show hint
Duplicate time and entity do not determine authority.
Show worked solution
Preserve both rows and resolve the conflict using an approved source version or priority and tie rule before joining. If no authoritative rule exists, quarantine the group; relying on whichever row happens to be last makes the result input-order dependent.
Check your solution
- The duplicated right key is (A,4).
- Neither conflicting value is chosen without authority.
16. Left D has a missing decision time and right R has a missing availability time. How should the pipeline handle them before merge_asof?
Show hint
Missing ordered keys cannot establish temporal eligibility.
Show worked solution
Quarantine or reject both records under the stated source policy before the as-of join. Record their IDs and reasons, then reconcile them with accepted rows; do not convert missing time to an arbitrary minimum or maximum.
Check your solution
- D has a missing left key.
- R has a missing right key.
17. A decision is 2026-01-03 00:00 UTC and a candidate is 2026-01-01 00:00 UTC. Test a two-day tolerance. If the source record instead became available one second after the two-day boundary, calculate whether it remains eligible.
Show hint
Both timestamps are timezone-compatible instants.
Show worked solution
The candidate is exactly two elapsed days old, so a backward tolerance of pd.Timedelta("2D") permits it. Confirm the source timestamps were correctly localized or converted to UTC; a calendar-day business rule may require a different contract. A candidate at Jan 1 00:00:01 UTC is one second less than two days old and remains eligible; a candidate one second earlier would be too old.
Check your solution
- The match age is two days.
- The tolerance boundary is met.
- A candidate one second after the boundary is within tolerance.
18. A left column is decision_time=8 and right column available_time=6. Specify join keys and a post-join age check. A tolerance of 1 is imposed; decide whether the age-2 candidate can still match.
Show hint
Preserve both differently named time columns.
Show worked solution
Use left_on="decision_time" and right_on="available_time" with backward direction. Before tolerance, the candidate is at 6, age 8-6=2. With tolerance 1 it is rejected, so the left row is retained unmatched. Record the candidate age separately from the final output.
Check your solution
- The unconstrained candidate has decision 8 and availability 6, age 2.
- With tolerance 1 the final result is unmatched.
19. Left decisions D1 at 1 and D2 at 5 join one value available at 4. Reconcile output identities and unmatched count. An independent expected decision D3 is absent from the left input; identify what the output count does and does not establish.
Show hint
A backward as-of join retains all left decisions.
Show worked solution
The output contains D1 and D2. D1 has no prior value and is unmatched; D2 matches time 4. Assert two output rows, exact left IDs and one missing match rather than using row count alone as proof of coverage. The two output rows prove preservation of D1,D2 only; compare against expected IDs to report missing D3.
Check your solution
- Output IDs are D1,D2.
- Unmatched count is 1 for D1.
- Expected D3 is absent despite preserving both input rows.
20. A decisions occur at 5 and 9; B at 6. Values A@4=10, B@5=20, A@10=30 are availability times. Use backward tolerance 2 and report matches.
Show hint
A’s later correction at 10 is not available at decision 9.
Show worked solution
A@5 matches A@4 with age 1; B@6 matches B@5 with age 1. A@9 cannot use A@10, and A@4 is five units old, outside tolerance, so it is unmatched. Retain all decision IDs and report the missing match.
Check your solution
- The first two matched values are 10 and 20.
- A@9 is unmatched under tolerance 2.
Key takeaways
- Match on information available at the decision time.
- Use sorting, grouping, and tolerance deliberately.
- Inspect source times and unmatched records after joining.
- Availability time can differ from event time.
- Backward direction alone does not prevent cross-entity or stale matches.
- Duplicate right times need an authoritative tie policy.