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
Andrew Drake
  • 655
  • 1
  • 11
  • 25

1 Answers1

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]
pythonic833
  • 3,054
  • 1
  • 12
  • 27
  • I had to add an extra check using https://stackoverflow.com/questions/36543606/python-pandas-check-if-dataframe-is-not-empty, but besides that it works! Clean too, thanks – Andrew Drake Aug 16 '19 at 14:23