How to get the index of the first non-zero value for a pandas dataframe column

Question:

I am trying to get the index of the first non-zero value for a specific column of a pandas dataframe.

import pandas as pd

df = pd.DataFrame(
    [[0,0,0],
    [0,0,3],
    [1,5,7],
    [8,7,3]],
    columns=['c1','c2','c3'])

print(df)

Output:

    c1  c2  c3
0   0   0   0
1   0   0   3
2   1   5   7
3   8   7   3

I would like to get an index position of value 5 (first non zero value) in column c2.

Asked By: tejas sangpal

||

Answers:

You can use boolean indexing combined with first_valid_index:

df.loc[df['c2'].ne(0), 'c2'].first_valid_index()

output: 2

NB. if there was only zeros in the column, the output would be None.

Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.