我想写一个多索引数据帧到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'
。
如何解决这个问题?
谢谢。
发布于 2019-12-10 15:27:34
在网上搜索之后,我用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()
发布于 2019-12-10 11:18:12
试一试
df.to_excel(r'data.xlsx', index = True)
参考:https://github.com/pandas-dev/pandas/issues/11292#issuecomment-447150410
https://stackoverflow.com/questions/59259628
复制相似问题