使用pandas向现有excelfile添加工作表

2024-10-01 17:35:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个excel文件。参与者完成实验,并将实验结果放入另一张表格中的两个excel文件中。每一个新的参与者都应该这样做。工作表名称为001002,…,取决于参与者编号。但是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)

因此,基本上它总是用正确的工作表名称创建这两个excelfiles,但是除了添加一个新的工作表之外,现有的工作表只会被新的工作表覆盖。我怎么解决这个问题?在

编辑:我发现使用openpyxl的工作簿,我可以在加载到工作簿后使用create_sheet在其中获取一个新的工作表,但是他们我却被困在如何用我创建的pandas.DataFrame编辑这个确切的工作表。在


Tags: 文件tonumpy名称dataframepandas参与者excel
1条回答
网友
1楼 · 发布于 2024-10-01 17:35:58

您应该创建一个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

相关问题 更多 >

    热门问题