Python Pandas - Return only those rows which have missing values

Given a Pandas DataFrame, we need to return only those rows which have missing values. By Pranit Sharma Last updated : September 26, 2023

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.

Problem statement

Let us suppose, we have a DataFrame that contains some missing values and we want to return a DataFrame that contains only those rows which contain these missing values.

Returning only those rows which have missing values

Pandas provides a method called isnull(), it returns those values which are null. If we want to apply this method row-wise, then we will pass axis=1 inside this parameter and if we want to apply this method column-wise, we will use axis=0 inside this parameter.

pandas.isnull() Method

This method is used to detect missing values for an array-like object.

The syntax of the isnull() method is:

pandas.isnull(obj)

Let us understand with the help of an example,

Python program to get/return only those rows of a Pandas dataframe which have missing values

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'Name':["Mohit","Anuj","Shivam","Sarthak","Priyanshu"],
    "Age":[np.nan,20,23,np.nan,19]
}

# Creating DataFrames
df = pd.DataFrame(d)

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

# Finding those rows having nan values
result = df[df.isnull().any(axis=1)]

# Display result
print("Result:\n",result)

Output

The output of the above program is:

Example: Return only those rows which have missing values

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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