For sample data frame that can be derived using code below, I want to update the column Offset_Date such that for any date in column Offset_Date that is not within column Date I want to replace that date in Offset_Date with last available value in column Date.
data = {"date": ['2021-01-01', '2021-01-03', '2021-01-04', '2021-01-05',
'2021-01-07', '2021-01-09', '2021-01-10', '2021-01-11'],
"offset_date": ['2021-01-02', '2021-01-04', '2021-01-05',
'2021-01-06', '2021-01-08', '2021-01-10',
'2021-01-11', '2021-01-12']}
test_df = pd.DataFrame(data)
test_df['date'] = pd.to_datetime(test_df['date'])
test_df['offset_date'] = pd.to_datetime(test_df['offset_date'])
To explain further in 1st row of above data frame date 2021-01-02 is not within column date so I want to replace that value with last available value in column date i.e. 2021-01-01.
I want to perform a vectorized approach so I tried the following, which lead to incorrect results.
test_df['offset_date_upd'] = np.where(test_df['offset_date'] in test_df['date'].values,
test_df['offset_date'],
test_df[test_df['date'] <= test_df['offset_date']].values.max())
How can I get the below desired output using a vectorized approach?
Desired Output
+------------+-------------+
| Date | Offset_Date |
+------------+-------------+
| 2021-01-01 | 2021-01-01 |
| 2021-03-01 | 2021-04-01 |
| 2021-04-01 | 2021-05-01 |
| 2021-05-01 | 2021-05-01 |
| 2021-07-01 | 2021-07-01 |
| 2021-09-01 | 2021-10-01 |
| 2021-10-01 | 2021-11-01 |
| 2021-11-01 | 2021-11-01 |
+------------+-------------+