首页 > 解决方案 > 如何在 python 中使用 xlsx writer 在现有 excel 中添加新列

问题描述

我需要在我现有的 Excel 工作表中添加一个新列,即 .xlsx,使用 Python 中的 Excel 编写器。

名称 |sub1 |sub2 |sub3。
内存。|10。|20。|30。
拉贾。| 11. | 22. | 33

我需要为 TOTAL 和 AVERAGE 添加新列,需要计算它并在 .xlsx 文件中显示输出。

需要在 Excel Writer 中做

标签: python-3.xopenxlsxpandas.excelwriterspreadsheet-excel-writer

解决方案


您可以将数据保存到xlsx文件中并使用 pandas 进行如下计算:

import pandas as pd 

df = pd.read_excel("test.xlsx")

total = df.sum(axis=1)  #sums all cells in row
average = df.mean(axis=1) #averages all cells in row

df.insert(loc = 4 , column = "Total", value = total )  #inserting sum to dataframe
df.insert(loc = 5 , column = "Average", value = average ) #inserting avg to dataframe

writer = pd.ExcelWriter("test.xlsx")
df.to_excel(writer,"Sheet1")    #Saving to df
writer.save()

你也可以用它df.to_excel("test.xlsx")来缩短写作步骤


推荐阅读