【问题标题】:Color column names in pandas data frame熊猫数据框中的颜色列名称
【发布时间】:2018-08-21 00:39:47
【问题描述】:

经过不同的操作,我在python中创建了一个高维数据框(df),其中列名如下:

  Product   Jan00   Feb00    ..  ..  Dec00   Service   Jan01  Feb01  ..  Country  ..

    ..       ..      ..      ..  ..    ..      ..        ..      ..   ..    ..

    ..       ..      ..      ..  ..    ..      ..        ..      ..   ..    ..

因此,列名是不同的时间序列(Jan00、Feb01 等)和一些词,如“产品”、“服务”和“国家”。我想将此数据框导出为 xlsx 格式,并且我想突出显示这 3 个词(产品、服务、国家/地区)。这是我用来在 excel 中导出输出的代码:

output_doc = pd.ExcelWriter('Project.xlsx')

df.to_excel(output_doc, sheet_name = 'TEST', index = False)

output_doc.save()

您能否建议我如何突出显示这 3 个列名(比如说用红色),以便在生成的 excel 电子表格中获得突出显示的格式? 提前致谢

【问题讨论】:

    标签: python excel pandas


    【解决方案1】:

    首先,您需要创建突出显示单元格的函数:

    def func():
        #here contidions for  highlighting the cells
        return ['background-color: red']
    

    现在您可以将此功能应用于您需要的单元格:

    data_frame.style.apply(func)
    

    第二个变种是:

    # Create a Pandas Excel writer using XlsxWriter as the engine.
    writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')
    
    # Convert the dataframe to an XlsxWriter Excel object.
    df.to_excel(writer, sheet_name='Sheet1')
    
    # Get the xlsxwriter workbook and worksheet objects.
    workbook  = writer.book
    worksheet = writer.sheets['Sheet1']
    
    # Apply a conditional format to the cell range.
    worksheet.conditional_format('B2:B8', {'type': '3_color_scale'})
    
    # Close the Pandas Excel writer and output the Excel file.
    writer.save()
    

    【讨论】:

      猜你喜欢
      • 2016-12-09
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      相关资源
      最近更新 更多