使用Pandas将Python创建的透视表写入Excel文档
我一直在致力于用python自动化一系列报告。我一直在尝试从导入的csv(binlift.csv)创建一系列透视表。我发现Panda库在这方面非常有用,但是,我似乎找不到任何东西可以帮助我将Panda创建的数据透视表写入excel文档(Template.xlsx),我想知道是否有人可以帮助我。到目前为止,我已经编写了以下代码使用Pandas将Python创建的透视表写入Excel文档,python,python-3.x,pandas,pivot-table,openpyxl,Python,Python 3.x,Pandas,Pivot Table,Openpyxl,我一直在致力于用python自动化一系列报告。我一直在尝试从导入的csv(binlift.csv)创建一系列透视表。我发现Panda库在这方面非常有用,但是,我似乎找不到任何东西可以帮助我将Panda创建的数据透视表写入excel文档(Template.xlsx),我想知道是否有人可以帮助我。到目前为止,我已经编写了以下代码 import openpyxl import csv from datetime import datetime import datetime import pandas
import openpyxl
import csv
from datetime import datetime
import datetime
import pandas as pd
import numpy as np
file1 = "Template.xlsx" # template file
file2 = "binlift.csv" # raw data csv
wb1 = openpyxl.load_workbook(file1) # opens template
ws1 = wb1.create_sheet("Raw Data") # create a new sheet in template called Raw Data
summary = wb1.worksheets[0] # variables given to sheets for manipulation
rawdata = wb1.worksheets[1]
headings = ["READER","BEATID","LIFTYEAR","LIFTMONTH","LIFTWEEK","LIFTDAY","TAGGED","UNTAGGEDLIFT","LIFT"]
df = pd.read_csv(file2, names=headings)
pivot_1 = pd.pivot_table(df, index=["LIFTYEAR", "LIFTMONTH","LIFTWEEK"], values=["TAGGED","UNTAGGEDLIFT","LIFT"],aggfunc=np.sum)
pivot_2 = pd.pivot_table(df, index=["LIFTYEAR", "LIFTMONTH"], values=["TAGGED","UNTAGGEDLIFT"],aggfunc=np.sum)
pivot_3 = pd.pivot_table(df, index=["READER"], values=["TAGGED","UNTAGGEDLIFT","LIFT"],aggfunc=np.sum)
print(pivot_1)
print(pivot_2)
print(pivot_3)
wb1.save('test.xlsx')enter code here
pandas中有一个选项可以写入“xlsx”文件。 在这里,我们基本上得到透视表的所有索引(在0级),然后逐个遍历这些索引以将表子集并写入表的该部分
writer = pd.ExcelWriter('output.xlsx')
for manager in pivot_1.index.get_level_values(0).unique():
temp_df = pivot_1.xs(manager, level=0)
temp_df.to_excel(writer, manager)
writer.save()
太好了,这段代码创建了一个新的excel工作簿。我是否可以将透视表附加到现有工作表(Template.xlsx)中。更具体地说,在特定的细胞范围内?