I need to create a new df that takes both the most recent date and the second most recent date for each store in the Date Time column; however, not all stores have a previous visit dates so some may need to return Nan.
df
| Store | Date Time |
|---|---|
| 100 | 2022-03-24 19:04:00 |
| 100 | 2022-05-05 10:29:00 |
| 100 | 2022-07-29 11:58:00 |
| 101 | 2022-03-15 08:56:00 |
| 102 | 2022-04-15 10:21:00 |
Resulting new df:
| Store | Previous Visit Date | Most Recent Visit Date |
|---|---|---|
| 100 | 2022-05-05 10:29:00 | 2022-07-29 11:58:00 |
| 101 | Nan | 2022-03-15 08:56:00 |
| 102 | Nan | 2022-04-15 10:21:00 |
I tried first to sort values by store than index. df = df.set_index('Store').sort_values(['Store', 'Date Time'])
I don't know how to integrate if store is unique take Most Recent Visit Date, if it has multiple entries pick the closet date = df['Most Recent Visit Date'] , and 2nd closest visit date = df['Previous Visit Date']. I might be making this more complicated than it needs to be.