excel - 将多标题 DataFrame 保存到 Excel 文件时如何避免写入空行?

标签 excel pandas dataframe header

我想将多头 DataFrame 保存为 Excel 文件。以下是示例代码:

import pandas as pd
import numpy as np

header = pd.MultiIndex.from_product([['location1','location2'],
                                     ['S1','S2','S3']],
                                    names=['loc','S'])

df = pd.DataFrame(np.random.randn(5, 6), 
                  index=['a','b','c','d','e'], 
                  columns=header)

df.to_excel('result.xlsx')
excel文件中有两个问题,如下所示:
enter image description here
问题 1:
标题下有一个空行。请让我知道如何避免 Pandas 在 Excel 文件中写入/插入空行。
问题 2:
我想保存没有索引的 DataFrame。但是,当我设置 index=False ,我收到以下错误:
 df.to_excel('result.xlsx', index=False)
错误:
NotImplementedError: Writing to Excel with MultiIndex columns and no index ('index'=False) is not yet implemented.

最佳答案

您可以创建 2 个数据框 - 只有标题和默认标题,并使用 startrow 将两者写入同一张表中范围:

header = df.columns.to_frame(index=False)
header.loc[header['loc'].duplicated(), 'loc'] = ''
header = header.T
print (header)
             0   1   2          3   4   5
loc  location1          location2        
S           S1  S2  S3         S1  S2  S3


df1 = df.set_axis(range(len(df.columns)), axis=1)
print (df1)
          0         1         2         3         4         5
a -1.603958  1.067986  0.474493 -0.352657 -2.198830 -2.028590
b -0.989817 -0.621200  0.010686 -0.248616  1.121244  0.727779
c -0.851071 -0.593429 -1.398475  0.281235 -0.261898 -0.568850
d  1.414492 -1.309289 -0.581249 -0.718679 -0.307876  0.535318
e -2.108857 -1.870788  1.079796  0.478511  0.613011 -0.441136

with pd.ExcelWriter('output.xlsx') as writer:  
    header.to_excel(writer, sheet_name='Sheet_name_1', header=False, index=False)
    df1.to_excel(writer, sheet_name='Sheet_name_1', header=False, index=False, startrow=2)

关于excel - 将多标题 DataFrame 保存到 Excel 文件时如何避免写入空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70431125/

相关文章:

python - Pandas 列在附加到新数据框后已排序

Java Selenium 使用 Apache POI - 读取 Excel 文件并将两行拉到一起

excel - 如何更快地写这个?

python - 将数据帧列分解为多行(TypeError : Cannot cast array data from dtype ('int64' ) to dtype ('int32' ))

android - 是否可以在 React Native 中使用 ExcelJS?

python - 循环遍历字典键的元素而不是枚举所有元素

pandas - 在seabornfacetGrid上绘制艺术家

python - 在 for 循环中将数据帧 append 在一起

python - 连接数据帧的片段

python-3.x - 与日期列的逻辑比较在Pandas数据框中不起作用