[SOLVED] find index where element change sign from 0 to 1

Issue

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

Solution

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

Answered By – richardec

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *