2

Let's say I want to get the first row of a dataframe where a certain column has negative value:

import pandas as pd
df = pd.DataFrame(columns=['c'],data=[[2.4,2.3,-1.0]])
index = df.loc[df['c'] < 0].index[0]

Now this works but in case I have a dataframe with millions of rows, I don't want to iterate over all of them to get the index. Is there a way to get the index without having to loop over each row? (Would be slow)

bilalt-j
  • 71
  • 3

1 Answers1

1

You can check which rows in a given column are negative with Series.lt and use idxmax to take the index of the first True:

df = pd.DataFrame(columns=['c'],data=[2.4,2.3,-1.0])
print(df)
    c
0  2.4
1  2.3
2 -1.0

df.c.lt(0).idxmax()
# 2
yatu
  • 86,083
  • 12
  • 84
  • 139