Easiest way to create a color gradient on excel using python/pandas?

前端 未结 1 1335
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-28 19:12

So I have data that I am outputting to an excel file using pandas\' ExcelWriter. After the entire data is outputted to the Excel file, what is the easiest way to apply condi

相关标签:
1条回答
  • 2020-12-28 19:48

    Here is an example of how to apply a conditional format to the XlsxWriter Excel file created by Pandas:

    import pandas as pd
    
    # Some sample data to plot.
    list_data = [30, 40, 50, 40, 20, 10, 5]
    
    # Create a Pandas dataframe from the data.
    df = pd.DataFrame(list_data)
    
    # Create a Pandas Excel writer using XlsxWriter as the engine.
    excel_file = 'testfile.xlsx'
    sheet_name = 'Sheet1'
    
    writer = pd.ExcelWriter(excel_file, engine='xlsxwriter')
    df.to_excel(writer, sheet_name=sheet_name)
    
    # Access the XlsxWriter workbook and worksheet objects from the dataframe.
    # This is equivalent to the following using XlsxWriter on its own:
    #
    #    workbook = xlsxwriter.Workbook('filename.xlsx')
    #    worksheet = workbook.add_worksheet()
    #
    workbook = writer.book
    worksheet = writer.sheets[sheet_name]
    
    # 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()
    

    The output looks like this:

    enter image description here

    See the XlsxWriter docs on Conditional Formatting to see how you can change the colours or other properties.

    See also Working with Python Pandas and XlsxWriter.

    0 讨论(0)
提交回复
热议问题