Python ProgrammingPython Programming

How to calculate the percent change at each cell of a DataFrame columns in Pandas?

Calculating the percent change at each cell of a DataFrame:

import pandas as pd

df = pd.DataFrame([[10, 20, 30, 40], [7, 14, 21, 28], [55, 15, 8, 12],
                   [15, 14, 1, 8], [7, 1, 1, 8], [5, 4, 9, 2]],
                  columns=['Apple', 'Orange', 'Banana', 'Pear'],
                  index=['Basket1', 'Basket2', 'Basket3', 'Basket4',
                         'Basket5', 'Basket6'])

print("\n------ Percent change at each cell of a Column -----\n")
print(df[['Apple']].pct_change()[:3])

print("\n------ Percent change at each cell of a DataFrame -----\n")
print(df.pct_change()[:5])


C:\pandas>python example.py
 
------ Percent change at each cell of a Column -----
 
            Apple
Basket1       NaN
Basket2 -0.300000
Basket3  6.857143
 
------ Percent change at each cell of a DataFrame -----
 
            Apple    Orange    Banana      Pear
Basket1       NaN       NaN       NaN       NaN
Basket2 -0.300000 -0.300000 -0.300000 -0.300000
Basket3  6.857143  0.071429 -0.619048 -0.571429
Basket4 -0.727273 -0.066667 -0.875000 -0.333333
Basket5 -0.533333 -0.928571  0.000000  0.000000
 
C:\pandas>