Home > Software engineering >  Calculate percentage change between two columns in python
Calculate percentage change between two columns in python

Time:05-11

I have dataframe df having revenue of 3 months by user, and need to find percent change between august and july using python,

user  revenuejune  revenuejuly  revenueaugust

Sam      231.13      1345.2        2455

Output

 user  revenuejune  revenuejuly  revenueaugust    change
    
    Sam      231.13      1345.2        2455.       82.5

CodePudding user response:

Use:

df['change'] = ((df['revenueaugust'] - df['revenuejuly'])/df['revenuejuly']*100)

Output:

  user  revenuejune  revenuejuly  revenueaugust     change
0  Sam       231.13       1345.2           2455  82.500743

CodePudding user response:

I am not sure I understood it right. But I guess you just need to add a new column based on a operation between coluns revenueaugust and revenuejuly.

import pandas as pd
import json

data = pd.DataFrame(
    {
        'name': ['Sam', 'Bob'],
        'revenuejune': [231.13, 200],
        'revenuejuly': [1345.2, 300],
        'revenueaugust': [2455, 400],
    }
)

data['change'] = (data['revenueaugust'] - data['revenuejuly'])/ data['revenuejuly'] * 100

print(data)

Output:

  name  revenuejune  revenuejuly  revenueaugust     change
0  Sam       231.13       1345.2           2455  82.500743
1  Bob       200.00        300.0            400  33.333333

CodePudding user response:

this should work for calculating the difference between august and july.

df["change"] = (df["revenueaugust."] - df["revenuejuly"]) / df["revenuejuly"] * 100
  • Related