0

I am trying to find the first transition value of a dataframe column as efficiently as possible. I would prefer not to have temporary variables. Say I have a dataframe (df) with a column of:

Column1  
0  
0
0
-1
1 

In this case, the value which I'm looking for is -1, which is the first time the value changes. I want to use this in an if statement for whether the value is first transitioning to 1 or -1. The pseudocode being:

if (first transition value == 1):
    # Something
elif: (first transition value == -1):
    # Something else

1 Answer 1

1

General case

You can compare the values in the dataframe to the first one, take only the differing values and use the first value of these.

df[df.Column1 != df.Column1.iloc[0]].Column1.values[0]

Special case

If you always want to find the first differing element from 0 you could just do it like this:

df[df.Column1 != 0].Column1.values[0]
Sign up to request clarification or add additional context in comments.

1 Comment

I had to add an extra check using stackoverflow.com/questions/36543606/…, but besides that it works! Clean too, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.