Pandas DataFrame pct_change() Method

Rate this post

Preparation

Before any data manipulation can occur, two (2) new libraries will require installation.

  • The Pandas library enables access to/from a DataFrame.
  • The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installations were successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required libraries.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import pandas as pd
import numpy as np 

DataFrame pct_change()

The pct_change() method calculates and returns the percentage change between the current and prior element(s) in a DataFrame. The return value is the caller.

To fully understand this method and other methods in this tutorial from a mathematical point of view, feel free to watch this short tutorial:

The syntax for this method is as follows:

DataFrame.pct_change(periods=1, fill_method='pad', limit=None, freq=None, **kwargs)
ParameterDescription
periodsThis sets the period(s) to calculate the percentage change.
fill_methodThis determines what value NaN contains.
limitThis sets how many NaN values to fill in the DataFrame before stopping.
freqUsed for a specified time series.
**kwargsAdditional keywords are passed into a DataFrame/Series.

This example calculates and returns the percentage change of four (4) fictitious stocks over three (3) months.

df = pd.DataFrame({'ASL':   [18.93, 17.03, 14.87],
                   'DBL':   [39.91, 41.46, 40.99],
                   'UXL':   [44.01, 43.67, 41.98]},
                   index=   ['2021-10-01', '2021-11-01', '2021-12-01'])

result = df.pct_change(axis='rows', periods=1)
print(result)
  • Line [1] creates a DataFrame from a dictionary of lists and saves it to df.
  • Line [2] uses the pct_change() method with a selected axis and period to calculate the change. This output saves to the result variable.
  • Line [3] outputs the result to the terminal.

Output

 ASLDBLUXL
2021-10-01NaNNaNNaN
2021-11-01-0.1003700.038837-0.007726
2021-12-01-0.126835-0.011336-0.038699

💡 Note: The first line contains NaN values as there is no previous row.


More Pandas DataFrame Methods

Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:

Also, check out the full cheat sheet overview of all Pandas DataFrame methods.