Pandas DataFrame first_valid_index() method with examples

Spread the love

The first_valid_index() method in pandas returns the index of the first occurrence of a row containing a non-NaN value. The check is performed row-wise, starting from the first row.

syntax –

dataframe.first_valid_index()

Examples –

Let’s read a dataset to work with.

import pandas as pd

url = 'https://raw.githubusercontent.com/bprasad26/lwd/master/data/fruit_prices.csv'
df = pd.read_csv(url)
df

Now, Let’s say we want to find the index of the first row that contains Non-NaN value. We can do this using the first_valid_index() method in pandas.

df.first_valid_index()
#output
0

Since the 0th row contains non-NaN values, Pandas return this row label.

Now, let’s drop the first row from the dataframe.

df.drop([0], inplace=True)

Now, Both 1st and 2nd row contains NaN values. Now if we check the first_valid_index() we should get the 3rd row label as it contains Non-NaN values.

df.first_valid_index()
#output
3

Rating: 1 out of 5.

Leave a Reply