0

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.

1
  • 1
    @JoshFriedlander you have to be sure there is at least one matching value ;) Commented Sep 22, 2022 at 12:14

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@AnoushiravanR idxmax would give an incorrect answer on a column of only zeros

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.