Jonathan
Jonathan

Reputation: 23

Pandas - Find the index for the first time a condition is true

I have data that looks something like this:

example = pd.Series([0,0,0,2,2,0], index = [2000, 2001, 2002, 2003, 2004, 2005])

How do I find the index corresponding to the first time that a condition is true?

For example, I want to find the index corresponding to the first nonzero entry, which in the example data is 2003.

Upvotes: 2

Views: 398

Answers (3)

Art3mis
Art3mis

Reputation: 109

example[example != 0].index[0]

Upvotes: 2

BENY
BENY

Reputation: 323316

By using nonzero

example.index[example.nonzero()[0][0]]
Out[267]: 2003

Upvotes: 2

zipa
zipa

Reputation: 27879

This will do it:

example.ne(0).idxmax()
#2003

Upvotes: 3

Related Questions