Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading