Felton Wang
Felton Wang

Reputation: 173

find index where element change sign from 0 to 1

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

Upvotes: 0

Views: 305

Answers (1)

user17242583
user17242583

Reputation:

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

Upvotes: 1

Related Questions