'Merging based on nearest values in pandas dataframe

I am trying my best to explain the issue im facing while doing merging.

I have two dataframes with timestamp unix numbers in common.

lets keep it as df1 and df2

df1
price1 timestamp
10     16454526519
23     16454527130
30     16454527200

df2
price2 timestamp
11     16454526518
24     16454527130
34     16454527205

if i merge based on df1, there is Nan values for the timestamps which are not present. I will forward fill those. I dont want that to be done because df2 may have timestamp a bit longer.

Merging behavior

timestamp     price1  price2
16454526519.   10.     nan
16454527130.   23.     24
16454527200.   30.     nan

Expecting behaviour

Want to merge in default manner and use forward or backward fill to remove nans and then demerge df1.

     timestamp     price1  price2
    16454526519.   10.     11
    16454527130.   23.     24
    16454527200.   30.     34

Note: i need to forward or backward fill only when it is lower than 5 seconds differance at max.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source