首页 > 解决方案 > ValueError 将多索引熊猫数据框转换为 Excel

问题描述

我正在尝试将多索引 pandas 数据框导出到 Excel,其中行索引和列标签完好无损。我还希望合并第一列中的“池”索引行,我相信 pd.to_excel 应该这样做。

我也尝试过openpyxl,但如果没有ValueError,似乎无法让它工作。我还尝试了 df=df.reset_index() 只是想看看我是否可以获得一个显示所有索引和列标签的平面文件,但这没有用。下面是代码和结果:

Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd
>>> import numpy as np
>>> import math
>>> s1arrays = [np.array(['Pool1', 'Pool1', 'Pool2', 'Pool2']),
...             np.array(['Rate1', 'Rate2', 'Rate1', 'Rate2'])]
>>> tuples = list(zip(*s1arrays))
>>> index = pd.MultiIndex.from_tuples(tuples, names=['Pool', 'Rate'])
>>> df = pd.DataFrame(np.random.randn(4, 3), columns=[2019, 2020, 2021], index=index)
>>> print(df)
                 2019      2020      2021
Pool  Rate                               
Pool1 Rate1  0.564911 -0.883633 -0.333450
      Rate2 -1.043308  1.543050  1.342350
Pool2 Rate1 -0.838110  2.287242 -1.285863
      Rate2  0.076783 -1.074720  0.801417
>>> df.to_excel('Test Output.xlsx', sheet_name='Sheet1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/generic.py", line 2127, in to_excel
    engine=engine)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/io/formats/excel.py", line 662, in write
    freeze_panes=freeze_panes)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/io/excel.py", line 1605, in write_cells
    xcell.value, fmt = self._value_with_fmt(cell.val)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/openpyxl/cell/cell.py", line 252, in value
    self._bind_value(value)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/openpyxl/cell/cell.py", line 218, in _bind_value
    raise ValueError("Cannot convert {0!r} to Excel".format(value))
ValueError: Cannot convert 'Pool1' to Excel

"Cannot convert {0!r} to Excel".format(value)) 在这种情况下是什么意思?

标签: excelpandasdataframemulti-index

解决方案


我尝试了您的代码并得到了正确的结果(我无法复制您的错误):

在此处输入图像描述

我有Python v. 3.7.0、Pandas v. 0.23.4 和Jupyter v. 1.0.0。也许你应该升级你的安装?

顺便说一句:您可以定义s1arrays为:

s1arrays = [['Pool1', 'Pool1', 'Pool2', 'Pool2'],
            ['Rate1', 'Rate2', 'Rate1', 'Rate2']]

另一个说明是文件名中的空格是不好的做法。将文件名更改为例如Test_Output.xlsx


推荐阅读