How does the pandas series.first_valid_index() method work?

PandasServer Side ProgrammingProgramming

The pandas series.first_valid_index() method is used to get the index of the first valid data. This means the first_valid_index() method returns the index of the first non_null element of the series.

It will return a single scalar based on the type of series index, and it will return None if the given series has all null/NA values or if it is empty. The first_valid_index() method doesn’t take any parameter.

Example 1

Let’s take a series object and try to retrieve the first valid index.

# importing packages
import pandas as pd
import numpy as np

# create a series
s = pd.Series([None, np.nan, 27, 61,np.nan, 34, 52, np.nan, 17], index=list('abcdefghi'))
print(s)

# apply first_valid_index() method
result = s.first_valid_index()

print("Result:")
print(result)

Explanation

Initially, we have created a pandas series object by using the pandas.Series constructor with a list of Nan’s and integer values and the index of the series is specified by an index parameter with a list of strings.

Output

The output is as follows −

a    NaN
b    NaN
c    27.0
d    61.0
e    NaN
f    34.0
g    52.0
h    NaN
i    17.0
dtype: float64

Result:
c

For the above example, the first valid index is “c”, because the elements at index positions a, b are Null/NA values.

Example 2

Here, let’s take an empty series object and see how the first_valid_index() method works for an empty series.

# importing packages
import pandas as pd

# create a series
sr = pd.Series([])
print(sr)

# apply first_valid_index() method
result = sr.first_valid_index()

print("Result:")
print(result)

Output

The output is given below −

Series([], dtype: float64)
Result:
None

The first_valid_index() method returned None for the empty series object.

Example 3

In this following example, we have created a pandas series object with all Null/Nan values and applied the first_valid_index() method to get the 1st valid index.

# importing packages
import pandas as pd
import numpy as np

# create a series
sr = pd.Series([None, np.nan])
print(sr)

# apply first_valid_index() method
result = sr.first_valid_index()

print("Result:")
print(result)

Output

The output is given below −

0    NaN
1    NaN
dtype: float64

Result:
None

For this example, also the first_valid_index() method returned None because there is no valid element available in the given series object.

raja
Updated on 07-Mar-2022 08:02:38

Advertisements