Pandas DataFrame first_valid_index() Method

5/5 - (1 vote)

Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

  • The Pandas library enables access to/from a DataFrame.
  • The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


FeFeel free to view the PyCharm installation guide for the required libraries.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
import numpy

DataFrame first_valid_index()

The first_valid_index() method returns the index for the first non-NA value or None if no NA value exists.

The syntax for this method is as follows:

DataFrame.first_valid_index()

This method contains no parameters.

Rivers Clothing has an issue with its pricing table. Therefore, they want to locate the first index (Small, Medium, or Large) that contains a valid price. To do this, run the following code.

idx = ['Small', 'Mediun', 'Large']

df = pd.DataFrame({'Tops':     [np.nan, np.nan, np.nan],
                   'Tanks':    [np.nan, 13.45, 14.98],
                   'Pants':    [np.nan, 56.99, 94.87]}, index=idx)
print(df)

result = df.first_valid_index()
print(result)
  • Line [1] creates an index for the DataFrame and saves it to idx.
  • Line [2] creates a DataFrame of incomplete inventory pricing, sets the index, and saves it to df.
  • Line [3] outputs the DataFrame to the terminal.
  • Line [4] retrieves the first valid (non-NA) value from the DataFrame and saves the index to result.
  • Line [5] outputs the result to the terminal.

Output

df

 TopsTanksPants
SmallNaN   NaN   NaN   
MediumNaN   13.45 56.99
LargeNaN   14.98 94.87

result: Medium

The first non-NA value occurs in the Medium index under the Tanks category.

More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.