I have an input dataframe that looks like this:
df = pd.DataFrame.from_dict({"t": [1,2,3,4,5], 'val': [100, 5, -4, -9, 1], })
I need to calculate the following 2 columns, one for the time since the last positive value, and one for the time since the last negative value:
df['t_since_neg'] = [np.nan, np.nan, np.nan, 1, 1]
df['t_since_pos'] = [np.nan, 1, 1,2,3]
The column t stands for time. How do I do this? I know it would have something to do with diff, but I couldn't get it to work exactly.
Update (follow up question): how would I do this if I have an additional column ‘id’, and the calculations need to be done within each group separately, ie each group is independent of each other?