Index of non 'NaN' values in Pandas

Given a pandas dataframe, we have to find the index of non 'NaN' values in Pandas.
Submitted by Pranit Sharma, on October 12, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

While creating a DataFrame or importing a CSV file, there could be some NaN values in the cells. NaN values mean "Not a Number" which generally means that there are some missing values in the cell. Hence, we need to find the index of fulfilled values.

Problem statement

Suppose we are given a DataFrame with some columns and some columns containing some NaN values but we only need to find out the index of non "NaN" values.

Finding the index of non 'NaN' values in Pandas

For this purpose, we will access all the values of the specific column and then apply the notnull() method to it. This method detects the non-missing values for an array-like object.

Let us understand with the help of an example,

Python program to find the index of non 'NaN' values in Pandas

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating two dictionary
d = {
    'A':[1,3,5,7,9],
    'B':[2,4,np.nan,8,np.nan]
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display DataFrame
print("DataFrame1:\n",df,"\n")

# Getting index
res = df[df['B'].notnull()]

# display result
print("Result:\n",res)

Output

The output of the above program is:

Example: Index of non 'NaN' values in Pandas

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.