将多层次的 Pandas 数据框导出到 Excel 时,如何消除索引?

3

I have a pandas dataframe as below:

header = [np.array(['location','location','location','location2','location2','location2']), 
np.array(['S1','S2','S3','S4','S5','S6'])] 
df = pd.DataFrame(np.random.randn(5, 6), columns = header ) 
df

我希望将数据框导出至 Excel 表格,但不需要索引。以下是我的代码,它可以将我的数据框导出至 Excel 表格,但会包括索引。当我使用参数 index=False 时,会出现错误。
# output all the consolidated input to an excel sheet
out_file_name = os.path.join(folder_location, "templates", future_template)
writer = pd.ExcelWriter(out_file_name, engine='xlsxwriter')
# Write each dataframe to a different worksheet.
df.to_excel(writer, sheet_name='Ratings Inputs')
# Close the Pandas Excel writer and output the Excel file.
writer.save()

索引值为 False 会给你什么错误? - Mntfr
1
这是我使用 index = False 时收到的错误信息:“NotImplementedError:尚未实现使用 MultiIndex 列且没有索引('index'=False)写入 Excel。” - Shanoo
那么发生的情况是您没有更新版本的pandas,如果我没记错的话,这是在0.17中实现的一个功能。只需更新您的pandas即可。 - Mntfr
1个回答

0

DataFrame.to_excel(index=False) 对于 MultiIndex 仍不被支持 (截至 Pandas 1.3.4,2021 年 10 月)。您将会得到以下错误:

NotImplementedError: Writing to Excel with MultiIndex columns and no index ('index'=False) is not yet implemented.

相反地,您可以尝试一些解决方案:

  1. 使用 index=True 进行写入,然后使用 openpyxl,重新打开文件,删除不需要的列/行,再次保存文件。这是一个较慢的过程,对于大型数据集可能不实用。

  2. 您可以手动编写 MultiIndex 标题。但这样将没有合并单元格。参见 如何隐藏行索引


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接