【问题标题】:Get rid of index while outputting multi header pandas dataframe to excel将多头熊猫数据框输出到excel时摆脱索引
【发布时间】:2019-07-26 00:08:24
【问题描述】:

我有一个如下的熊猫数据框:

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 给你什么错误?
  • 这是我收到的错误消息 index = False "NotImplementedError: Writing to Excel with MultiIndex columns and no index ('index'=False) is not yet implemented."
  • 哦,如果我没记错的话,你没有更新版本的 pandas 这是 0.17 中实现的功能。只需更新您的熊猫。

标签: python-3.x pandas


【解决方案1】:

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 标头。不过,这不会合并单元格。见How to hide the rows index

【讨论】:

    猜你喜欢
    • 2015-05-11
    • 2019-09-28
    • 2016-12-21
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 2016-06-13
    相关资源
    最近更新 更多