【问题标题】:unable to write multi-index dataframe to excel无法将多索引数据框写入 excel
【发布时间】:2020-04-03 04:35:11
【问题描述】:

我想写一个多索引数据框到excel:

col = [['info', '', 'key'], ['alert', 'date', 'price'], ['alert', 'date', 'amount']]
df = pd.DataFrame(columns = pd.MultiIndex.from_tuples(col))
df.loc[0, :] = np.random.random(3)
df.to_excel('data.xlsx', index = False)

但是,出现错误:

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

我检查了 pandas 版本:pd.__version__,结果是'0.25.3'

如何解决问题?

谢谢。

【问题讨论】:

标签: pandas


【解决方案1】:

在网上搜索后,我用pywin32解决了问题。

import win32com.client as win32
df.to_excel('data.xlsx', index = True)
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.DisplayAlerts = False
wb = excel.Workbooks.Open('data.xlsx')
excel.Visible = True
ws = wb.Worksheets('Sheet1')
ws.Columns(1).EntireColumn.Delete()
wb.SaveAs('data.xlsx')
excel.Application.Quit()

【讨论】:

    【解决方案2】:

    试试

    df.to_excel(r'data.xlsx', index = True)

    参考:https://github.com/pandas-dev/pandas/issues/11292#issuecomment-447150410

    【讨论】:

    • 如果设置index为True,excel文件中会多出一列。如何删除该列?
    • 请参考修改后的问题。
    • 谁能帮忙?
    • 添加评论以便稍后返回。另外,我也在等待这个问题的答案。
    猜你喜欢
    • 2016-02-16
    • 2016-08-23
    • 2018-02-26
    • 2019-05-10
    • 2020-12-16
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    相关资源
    最近更新 更多