excel - 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)) 在这种情况下是什么意思?
解决方案
推荐阅读
- multithreading - 对于 Celery 中的 IO 绑定任务,我应该使用哪个 worker_concurrency?
- r - 如何通过循环从 UN Comtrade API 中提取数据?
- python - 我如何将这个 python 代码精确到几行?
- wordpress - 如何在 AWS 云端设置 wordpress 网站?
- javascript - mssql - 流模式下的 uncaughtException
- javascript - 如何从两个不同长度的数组javascript创建对象数组
- c# - 如何在 ASP.NET Core 5.0 中处理来自客户端的双重请求?
- excel - 使用 VB.NET 使用 VBA 代码将特定单元格的值写入工作簿
- firebase - 使用firebase在nestjs中登录并注册
- java - OnClickListner 在 Android 的 View 类中描述了什么?