【问题标题】:Adding sheets to existing excelfile with pandas使用 pandas 将工作表添加到现有的 excelfile
【发布时间】:2016-03-30 20:34:47
【问题描述】:

我有两个 excel 文件。参与者完成实验,结果应输入到另一张纸上的两个 excel 文件中。这应该发生在每个新参与者身上。工作表名称是 001,002,...,取决于参与者编号是什么。但是 excelfiles 只是不断被覆盖。

我正在使用的代码:

import pandas
allmeans = numpy.array([[(meanreactiontimeinputsusercongruentpositief),(meanreactiontimeinputsusercongruentnegatief),(meanreactiontimeinputsuserincongruentposneg), (meanreactiontimeinputsuserincongruentnegpos), (meanvalueinputusercongruentpositief), (meanvalueinputusercongruentnegatief), (meanreactiontimeinputsuserincongruentposneg), (meanvalueinputuserincongruentnegpos)]])
to_write = pandas.DataFrame({'Age': age, 'Gender': gender, 'MeanReactionTimeCongruentPos': allmeans[:,0], 'MeanReactionTimeCongruentNeg': allmeans[:,1], 'MeanReactionTimeIncongruentPosNeg': allmeans[:,2], 'MeanReactionTimeIncongruentNegPos': allmeans[:,3], 'MeanValueInputCongruentPos': allmeans[:,4], 'MeanValueInputCongruentNeg': allmeans[:,5], 'MeanValueInputIncongruentPosNeg': allmeans[:,6], 'MeanValueIncongruentNegPos': allmeans[:,7]})
to_write.to_excel('MeansOfUsers.xlsx',sheet_name = str(participantnumber), index = False, startrow = 3, startcol = 2)

allresults= numpy.array([listofrandomizedconditions,inputsuser,reactiontimesuser])
to_write2 = pandas.DataFrame({'Conditions': allresults[0,:], 'Inputs': allresults[1,:], 'Reactionstimes': allresults[2,:]})
to_write2.to_excel('ResultsofUsers.xlsx',sheet_name = str(participantnumber), index = False, startrow=3,startcol=2)

所以基本上它总是使用正确的工作表名称创建这 2 个 excel 文件,但除了添加新工作表之外,现有工作表只会被新工作表覆盖。我该如何解决?

编辑:我发现使用 openpyxl 的工作簿,我可以在加载工作簿后使用 create_sheet 在其中获取新工作表,但是我坚持如何使用 pandas.DataFrame 编辑该确切工作表我创建。

【问题讨论】:

标签: python excel numpy pandas


【解决方案1】:

您应该创建一个ExcelWriter 对象并使用它来保存数据帧。您需要调用其save() 方法才能实际保存excel 文件。

import pandas as pd

ew = pd.ExcelWriter('a.xlsx')
pd.DataFrame({'a':[1,2]}).to_excel(ew, sheet_name='a')
pd.DataFrame({'a':[1,2]}).to_excel(ew, sheet_name='b')
ew.save() # don't forget to call save() or the excel file won't be created

【讨论】:

  • 我测试过了,但还是没有在de excelfile中新建表格,只是覆盖了已有的表格;可能是因为每次实验运行时,整个代码都会运行,并且 ew 创建一个新的 excelfile,它与已经存在的 excelfile 具有相同的名称。这会被一个新的 excel 文件覆盖。如果我可以创建一个 ew,运行实验 X 次并将 X 个数据帧添加到 ew,然后保存 ew,那么你给我的内容会有所帮助。但是实验运行 X 次,每次制作一个 ew 和一个 ew2(因为我需要 2 个 excelfiles)。我应该打开(或创建)一个名为“x”的 excel 文件并添加一个工作表。
猜你喜欢
  • 1970-01-01
  • 2018-03-22
  • 2019-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-05
相关资源
最近更新 更多