Pandas How To Uncategorized How to calculate percent change

How to calculate percent change

In this post I show you how to calculate percent change in Pandas. You will also learn how to add a percentage change column to the dataframe.

Pandas offers in its wide range of functions one that calculates the percentage change. Use the pct_change function to calculate the percentage change.

How to calculate percent change in Pandas dataframe

I will use the following dataframe example.

import pandas as pd

my_df = pd.DataFrame({'Column1': [2, 5, 7, 46],
                      'Column2': [12, 21, 5, 22],
                      'Column3': [8, 22, 9, 12]})

print(f'This is my sample dataframe \n{my_df}')

Sample dataframe for percent change in Pandas

I would like to calculate the percentage change for column number 3. To calculate the percentage change in column 3, I use the pct_change function.

import pandas as pd

my_df = pd.DataFrame({'Column1': [2, 5, 7, 46],
                      'Column2': [12, 21, 5, 22

],
                      'Column3': [8, 22, 9, 12]})


my_df['Coulmn3_Pct_Change'] = my_df['Column3'].pct_change().round(4)*100
print(f'This is the percent change of values \n{my_df}')

The proof that the code is very simple is that I didn’t even use any parameters to the pct_change function.

how to calculate percent change in Pandas

In my Python code, I created a new column in which Pandas calculated the percentage change in the data from column 3. For a neater notation, I multiplied the values by 100 and rounded to two decimal places.

You already know the method to calculate percentage changes in a Pandas dataframe. The pct_change function offers more possibilities. To learn about the possibilities of the pct_change function, I paste the link to the documentation below.

See also:
How to calculate sum of rows and columns in Pandas
Pct-change documentation
How to calculate standard error in Pandas
How to calculate business days

1 thought on “How to calculate percent change”

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post