I cant use external libraries other than pandas or numpy
If I had a dataframe like
import pandas as pd
d = pd.DataFrame({'purchase_date':[datetime(2022,1,5),datetime(2022,12,10)],'shop_visits':[[datetime(2021,1,4),datetime(2022,1,6),datetime(2022,1,7)],[datetime(2022,5,30),datetime(2022,9,30),datetime(2022,12,10)]]})
| purchase_dt | shop_visits |
|---|---|
| 2022-01-05 | [2022-01-04,2022-01-06,2022-01-07] |
| 2022-12-10 | [2022-05-30,2022-09-30,2022-12-10] |
I would need a function that returns 2022-01-06 for the first row and 2022-12-10 for the second, because both are the closest dates on the list after purchase_dt.
I have a function with apply already that does the min with my own lambda key, but its taking too long and I want to vectorize:
d.apply(lambda x: min([d for d in x['shop_visits'] if d >= x['purchase_date']],key=lambda d: d-x['purchase_date']),axis=1)
The thing is that I am not sure if this can be done using numpy.