Home > Blockchain >  find index where element change sign from 0 to 1
find index where element change sign from 0 to 1

Time:03-15

I have a DataFrame like below, where I want to find index where element goes from 0 to 1.

Below code gets all the instances I want, however it also includes cases where sign changes from -1 to 0, which I don't want.

import numpy as np

df=pd.DataFrame([0,1,1,1,0,1,0,-1,0])
df[np.sign(df[0]).diff(periods=1).eq(1)]

Output:

    0
1   1
5   1
8   0

CodePudding user response:

Just add another condition:

filtered = df[np.sign(df[0]).diff(1).eq(1) & np.sign(df[0]).eq(1)]

Output:

>>> filtered
   0
1  1
5  1

CodePudding user response:

You could use diff and shift (to make sure the previous element was 0):

out = df[df.diff().eq(1) & df.shift().eq(0)].dropna()

Then again, we don't even need diff since the difference is always 1, so just shift is enough:

out = df[df[0].eq(1) & df[0].shift().eq(0)]

Output:

     0
1  1.0
5  1.0
  • Related