Distance between values in dataframe

Viewed 75

I have a dataframe that contains a series of dummy variables that indicates types of events (e1, e2) taking place up to another event (a).

I need to know the distance in index value from each event of type "e1" and "e2" and up to the next event "a". I have tried to demonstrate using the shown data.

I have looked at some solutions, including scipy.spatial and interpolate, but I cannot really wrap my head around how to use those to solve my issue.

df = pd.DataFrame({'index': [240, 251, 282, 301, 321, 325, 328, 408], 'a': ['0','0','0','0','1','0','0','1'], 'e1': ['0','1','0','0','0','0','1','0'], 'e2': ['1','0','1','0','0','1','0','0']})
df.set_index('index', inplace=True)
dfTarget = pd.DataFrame({'index': [240, 251, 282, 301, 321, 325, 328, 408], 'a': ['0','0','0','0','1','0','0','1'], 'e1': ['0','70','0','0','0','0','80','0'], 'e2': ['81','0','39','0','0','83','0','0']})
dfTarget.set_index('index', inplace=True)

print(df)
print("------")
print(dfTarget)

       a e1 e2
index         
240    0  0  1
251    0  1  0
282    0  0  1
301    0  0  0
321    1  0  0
325    0  0  1
328    0  1  0
408    1  0  0
------
       a  e1  e2
index           
240    0   0  81
251    0  70   0
282    0   0  39
301    0   0   0
321    1   0   0
325    0   0  83
328    0  80   0
408    1   0   0
1 Answers

IIUC, you could use:

cols = ['e1', 'e2']
s = df.index.to_series().mask(df['a'].ne('1')).bfill()-df.index

df[cols] = df[cols].mask(df.eq('1'), s, axis=0).astype(int)

output:

       a  e1  e2
index           
240    0   0  81
251    0  70   0
282    0   0  39
301    0   0   0
321    1   0   0
325    0   0  83
328    0  80   0
408    1   0   0
Related