Home »
Python »
Python Programs
Comparing previous row values in Pandas DataFrame
Learn, how to compare previous row values in Pandas DataFrame in Python?
Submitted by Pranit Sharma, on February 18, 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
Suppose that we are given a pandas DataFrame, we need to create another column that compares the previous row of a column to see if they are equal.
Pandas DataFrame - Comparing previous row values
For comparing previous row values, we need eq with shift method so that it checks each value whether it is equal or not, and also it automatically shifts to another value.
Let us understand with the help of an example,
Python program to compare previous row values in Pandas DataFrame
# Importing pandas package
import pandas as pd
# Import numpy
import numpy as np
# Creating a dataframe
df = pd.DataFrame({'col':[1,3,3,1,2,3,2,2]})
# Display the DataFrame
print("Original DataFrame:\n",df,"\n\n")
# Comparing previous row values
df['check'] = df.col.eq(df.col.shift())
# Display Result
print("Result:\n",df)
Output
The output of the above program is:
Python Pandas Programs »