简体   繁体   English

通过使用 Python 应用 Excel 公式创建新的数据框列

[英]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.我有一个 excel 电子表格,我正在使用 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.我有第二个 excel 文件,其中包含一些需要应用于第一个 excel 以创建新列的公式。 My dataframe of first excel looks somewhat like this:我的第一个 excel 数据框看起来有点像这样:

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:根据第二个 excel,我想减去RPA RejRPA Acc的值,并用它们的结果创建一个新列Total并将整个数据框写入一个 excel 文件,我通过这个实现了:

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:但是当我点击Total列中的值时,我想查看 excel 公式,如下所示:

在此处输入图片说明

I don't know how to do arithmetic operations on python using excel formulas.我不知道如何使用 excel 公式对 python 进行算术运算。 If you guys could help me achieve this, I'd really appreciate that如果你们能帮助我实现这一目标,我将不胜感激

you can write formulas to each row using a for loop.您可以使用 for 循环将公式写入每一行。

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:输出: 输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM