Search code examples
pythonpandasdataframerow

Python, Pandas: Find first row-index with exact condition


Good evening,

my Dataframe is looking something like this:

name    |    age
name_a  |    27
name_b  |    59
name_c  |    41
...
name_z  |    38

How can I find the first row - and getting the index - where a certain condition, let's say "age" >= 40 is fitting?

Thanks for all your help and a great evening to all of you!


Solution

  • You can first sort_values on age:

    df = df.sort_values('age')
    

    Then take head(1) after using the condition and sub setting the dataframe based on the condition.

    df[df['age']>40].head(1)
    
         name  age
    2  name_c   41