Python | Pandas Series.first_valid_index ()

Python Methods and Functions

Series.first_valid_index() Pandas Series.first_valid_index() returns the index for the first non-NA / zero value in this series object.

Syntax: Series.first_valid_index ()

Parameter: None

Returns: scalar: type of index

Example # 1: Use Series.first_valid_index () to find the first valid index in a given series object.

# import pandas as pd

import pandas as pd

 
# Create series

sr = pd.Series ([ None , 25 , 3 , 25 , 24 , 6 ])

 
# Create Index

index_ = [ 'Coca Cola' , 'Sprite' , ' Coke' , 'Fanta' , 'Dew' , ' ThumbsUp' ]

 
# set index

sr.index = index_

 
# Print series

print (sr)

Output:

We will now use Series.first_valid_index () to find the first valid index in a given series object.

# return the first valid index

result = sr .first_valid_index ()

 
# Print the result tat

print (result)

Output:


As we can see in the output, Series.first_valid_index () successfully returned the first valid index of this series object.

Example # 2: Use Series.first_valid_index () to find the first valid index on a given series object.

# import pandas as pd

import pandas as pd

 
# Create series

sr = pd.Series ([ N one , None , None , 18 , 65 , None , 32 , 10 , 5 , 24 , None ])

 
# Create index

index_ = pd.date_range ( '2010-10-09' , periods = 11 , freq = 'M' )

 
# set index

sr.index = index_

  
# Print series

print (sr)

Exit:

Now we will use Series.first_valid_index () to find the first valid index in a given series object.

# return the first valid index

result = sr.first_valid_index ()

 
# Print the result

print ( result)

Output:

As we can see in the output, Series.first_valid_index () successfully returned the first valid the index of this series object.





Get Solution for free from DataCamp guru