I want to shift a pandas column by an amount of time, and reindex the dataframe to accommodate this shift. Take the following dataframe:
df = pd.DataFrame({"Col1": [10, 20, 15, 30, 45],
"Col2": [13, 23, 18, 33, 48],
"Col3": [17, 27, 22, 37, 52]},
index=pd.date_range("11:00", "13:00", freq="30min"))
I would like to shift Col1 by 15 minutes and have the datetime index of the dataframe be updated to allow for these new values. However, if I shift Col1 by 15 minutes, you can see that because it doesn't align with the index, the entire column is just set to NaN values:
df["Col1"] = df["Col1"].shift(15, freq="T")
print(df)
Col1 Col2 Col3
2021-03-25 11:00:00 NaN 13 17
2021-03-25 11:30:00 NaN 23 27
2021-03-25 12:00:00 NaN 18 22
2021-03-25 12:30:00 NaN 33 37
2021-03-25 13:00:00 NaN 48 52
I would like the dataframe to look like this:
Col1 Col2 Col3
2021-03-25 11:00:00 NaN 13.0 17.0
2021-03-25 11:15:00 10.0 NaN NaN
2021-03-25 11:30:00 NaN 23.0 27.0
2021-03-25 11:45:00 20.0 NaN NaN
2021-03-25 12:00:00 NaN 18.0 22.0
2021-03-25 12:15:00 15.0 NaN NaN
2021-03-25 12:30:00 NaN 33.0 37.0
2021-03-25 12:45:00 30.0 NaN NaN
2021-03-25 13:00:00 NaN 48.0 52.0
2021-03-25 13:15:00 45.0 NaN NaN
(which I created with the following code:)
df = pd.DataFrame({"Col1": [float('nan'), 10, float('nan'), 20, float('nan'), 15, float('nan'), 30, float('nan'), 45],
"Col2": [13, float('nan'), 23, float('nan'), 18, float('nan'), 33, float('nan'), 48, float('nan')],
"Col3": [17, float('nan'), 27, float('nan'), 22, float('nan'), 37, float('nan'), 52, float('nan')]},
index=pd.date_range("11:00", "13:15", freq="15min"))
If there are any suggestions for this that would be greatly appreciated!