Pandas compare next row

Given a pandas dataframe, we have to compare multiple rows.
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.

Problem statement

Suppose we are given with a DataFrame with some columns and values and now we need t compare first and second row. Suppose we have three columns a, b, and c.

We need to apply multiple conditions to these columns so thar we can compare pandas DataFrame rows.

Comparing multiple rows

To compare next row, we will first create a DataFrame and just after that we will shift each column by 1 and store them in other columns which will act like an offset of each column respectively and then we will compare them.

Let us understand with the help of an example,

Python program to compare multiple rows in pandas DataFrame

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating two dictionary
d = {

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

# Display DataFrame

# Creating offsets
df['A_shift'] = df['A'].shift(-1)
df['B_shift'] = df['B'].shift(-1)
df['C_shift'] = df['C'].shift(-1)

# Comparing the rows
df['result'] = (df['A'] == df['A_shift']) & (df['B'] < df['B_shift']) & (df['C'] == df['C_shift'])

# display result


Example: Pandas compare next row

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.