How do I subtract the previous row from the current row in a pandas dataframe and apply it to every row; without using a loop?

Learn, how do I subtract the previous row from the current row in a pandas dataframe and apply it to every row; without using a loop?
Submitted by Pranit Sharma, on December 01, 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 the dataframe with multiple columns all off with numerical values and we need to subtract a row value before the current row value. We need to calculate the percentage difference between these two-row values and also, and we need to apply this type of computation on each row.

Subtracting the previous row from the current row in a pandas dataframe

Pandas provide us pct_change() method which means the percentage change method. This method calculates the percentage change between the row values by default it calculates the difference from the current row with the prior row to the current row.

Hence, we will use this method.

Let us understand with the help of an example,

Python program to subtract the previous row from the current row in a pandas dataframe and apply it to every row; without using a loop

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a DataFrame
df = pd.DataFrame({
    'A':[1042,223,367,345],
    'B':[173,894,398,814]
})

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

# Using pct change method
res = df.B.pct_change() * 100

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

Output

The output of the above program is:

Example: Creating a new column in Pandas by using lambda function on two existing columns

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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