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

Time:09-22

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.

CodePudding user response:

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.

  • Related