To calculate percentage change in pandas, we use the pct_change() method. You can calculate percentage change for a series or a dataframe. By default the pct_change() method calculates Percentage change between the current and a prior element.
Formula of Percentage change –
Let’s read a dataset to work with.
import pandas as pd url = 'https://raw.githubusercontent.com/bprasad26/lwd/master/data/ICICIBANK.NS.csv' df = pd.read_csv(url) df.head()
1 . Calculate Percentage change along the index axis –
By default, the pct_change() method calculate the percentage change for a column.
Let’s say we want to calculate the percentage change for the Open column.
By default, pandas uses the current row and the previous rows for calculating percentage change. But you can change it using the periods parameter.
Let’s say you want to calculate percentage change between the current row and 3 rows before that.
2 . Calculate Percentage change along the column axis –
To calculate percentage change for each rows we need to set the axis parameter to axis=1 or columns.
Let’s say we want to know the percentage change in opening price and closing price.