Alana O'Neill
Alana O'Neill

Reputation: 81

Do operation based on a current event index, and the index of the next event of another column [pandas]

Ok so this one is very hard to describe. So i will just put together an example to explain.

pd.DataFrame({'event_a': [False, True, False, False, False, True, False, False, False, True, False],
              'event_b': [False, False, False, True, False, False, False, False, True, False, False],
              'value': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]})

Here we have two events and a value columns. The events will always alternate (there will never be event a and event b in the same index, and there will never be two of the same events in a row without the other event in between)

my specific operation i want to perform is abs(next_value / current_value - 1)

Given this, my output for this example should look like...

output = [na, 1, na, 0.5, na, 0.5, na, na, 0.111, na, na]

Row 2 for example is abs(4 (value of next event) / 2 (current event) - 1) = 1

Upvotes: 0

Views: 15

Answers (1)

Ayoub ZAROU
Ayoub ZAROU

Reputation: 2417

try doing:

cond = df.loc[:, ['event_a', 'event_b']].any(axis=1)
output = np.ones(cond.size) * np.nan
output[cond] = (t.loc[cond, 'value'].shift(-1) / t.loc[cond, 'value']).subtract(1).abs()

Upvotes: 1

Related Questions