vesuvius
vesuvius

Reputation: 435

Create a new dataframe column by applying Excel formula using Python

I have an excel spreadsheet which I am reading into a dataframe using pandas. I have a second excel file which contains some formulas which need to be applied on the first excel in order to create a new column. My dataframe of first excel looks somewhat like this:

RPA Rej    RPA Acc
  1          0
  5          3
  0          0

As per the second excel, I want to subtract the values of RPA Rej and RPA Acc and create a new column Total with their result and write the whole dataframe into an excel file, which I very much achieved by this:

df['Total'] = df['RPA Rej'] - df['RPA Acc']

and this:

df.to_excel('data.xlsx', index = False)

but I want to see the excel formula when I click on the values in Total column , something like this:

enter image description here

I don't know how to do arithmetic operations on python using excel formulas. If you guys could help me achieve this, I'd really appreciate that

Upvotes: 4

Views: 6265

Answers (1)

Dimitris Thomas
Dimitris Thomas

Reputation: 1393

you can write formulas to each row using a for loop.

import pandas as pd
import numpy as np

# Create a test dataframe
df = pd.DataFrame({'RPA Rej': [1,5,0],
                    'RPA Acc': [0,3,0]})

# Insert an empty column to write the formulas
df.insert(2, 'TOTAL', np.nan)

# Start the xlsxwriter
writer = pd.ExcelWriter('Test Formulas.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Create a for loop to start writing the formulas to each row
for row in range(2,df.shape[0]+2):
    formula = f'=A{row}-B{row}'
    worksheet.write_formula(f"C{row}", formula)

writer.save()

Output: Output

Upvotes: 7

Related Questions