【问题标题】:Using pandas dataframe style for adjusting column width [duplicate]使用熊猫数据框样式调整列宽[重复]
【发布时间】:2020-08-28 07:22:07
【问题描述】:

我有一个dataframedf:

A                               B                  LongColName1     AnotherNa   AnotherName3
Brunner Island is not island    Baltimore is town  0.26             3.88        3.75
Brunner Island is not island    Baltimore is town  -0.59            1.47        2.01

当我将上述数据框转储到 excel 时,它在 excel 中显示如下:

有没有办法设置数据框的样式,以便转储到 excel 如下所示:

【问题讨论】:

    标签: python pandas dataframe python-3.8 pandas.excelwriter


    【解决方案1】:

    一种方法可能是在写入 excel 时找到列的最大长度并明确设置该列的宽度。

    考虑下面的数据框:

    In [527]: df                                                                                                                                                                                                
    Out[527]: 
                                     A
    0     Brunner Island is not island
    1  Brunner Island is not an island
    
    len_max = df.A.str.len().max()
    
    from StyleFrame import StyleFrame
    
    excel_writer = StyleFrame.ExcelWriter(filename)
    sf = StyleFrame(df)
    sf.set_column_width(columns=['A'],width=len_max)
    
    sf.to_excel(excel_writer=excel_writer)
    excel_writer.save()
    

    【讨论】:

      【解决方案2】:

      无法自动调整列宽。但是这篇文章中提到了一些解决方法Is there a way to auto-adjust Excel column widths with pandas.ExcelWriter?

      【讨论】:

        猜你喜欢
        • 2019-10-04
        • 2020-08-03
        • 2021-09-17
        • 2019-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-05
        相关资源
        最近更新 更多