4

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

2
  • 1
    are you saying you want to write excel formulas into columns then export that ? - if so, why not just do it in excel? Commented Jan 23, 2020 at 10:41
  • 1
    Actually, it was being done in excel only, but I am creating sort of an automation tool which with a press of a button will create a new excel applying the formulas of the previous excel hence, reducing the hassle of doing it manually Commented Jan 23, 2020 at 10:46

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.