Search code examples
excelpandasdataframemulti-index

ValueError converting multi-index pandas dataframe to Excel


I'm trying to export a multi index pandas dataframe to Excel with the row indexes and column labels intact. I also want the "Pool" index rows in the first column to be merged, which I believe pd.to_excel is supposed to do.

I've tried openpyxl as well, but cannot seem to get this to work without the ValueError. I also tried df=df.reset_index() just to see if I could get a flat file showing all the index and column labels, and that didn't work. Below is the code and results:

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

What is the meaning of "Cannot convert {0!r} to Excel".format(value)) in this context?


Solution

  • Problem is in old version of pandas, for me it working nice in last version:

    pandas 0.24.2
    openpyxl: 2.4.10
    xlrd: 1.1.0
    xlwt: 1.3.0
    xlsxwriter: 1.0.2 
    

    So please upgrade your pandas version.