【问题标题】:How to avoid writing an empty row when I save a multi-header DataFrame into Excel file?将多标题 DataFrame 保存到 Excel 文件中时如何避免写入空行?
【发布时间】:2022-01-22 14:52:25
【问题描述】:

我想将一个多头数据框保存为 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文件中有两个问题如下图所示:

问题 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.

【问题讨论】:

    标签: excel pandas dataframe header


    【解决方案1】:

    您可以创建 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)
    

    【讨论】:

    • 谢谢。有什么办法可以避免重复列名“location1”和“location2”? (就像我上传的图片)。
    • @Mohammad - 答案已编辑,部分header
    猜你喜欢
    • 2016-03-26
    • 2015-11-25
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多