How to Find first occurrence of a bool starting from index

Viewed 128
          A         B         C         D
123  0.132003 -0.827317 -0.076467      True
124  1.130127 -1.436737 -1.413681      True
125  1.024180  0.569605  0.875906      True
126  0.974466 -2.006747 -0.410001      False
127  0.545952 -1.219217 -1.226825      False
128 -1.281247 -0.727707 -0.121306      True

Hi, how to I find in pandas dataframe the first occurrence of a given bool (i.e. False for this case) starting from a given index (i.e. 123 for this case)? And finally return that particular row.

3 Answers

You could try idxmin:

>>> df['D'].idxmin()
126
>>> 

For true values you could do idxmax:

>>> df['D'].idxmax()
123
>>> 

But let's say if D column is something like:

>>> df['D']
123    foo
124    bar
125    foo
126    bar
127    foo
128    bar
Name: D, dtype: object

Then you want the first bar, you could do:

>>> df['D'].eq('bar').idxmax()
124
>>> 

You could do something like:

import pandas as pd
import numpy as np

df = pd.DataFrame({'A': np.random.rand(5), 'B': [True, True, True, False, False]})

first_occ = np.where(df['B'] == False)[0][0] # 3

In your case

df[~df.D].drop_duplicates('D')
Out[47]: 
            A         B         C      D
126  0.974466 -2.006747 -0.410001  False
Related