pythonpandascsvjupyter-notebook

how to export data frame with color to csv


I want to add color to cells of Status Pass and Fail. I tried following code it will print a colored data frame but exported csv was not colored.

And when I applied two rules (green and red), only green shows.

df = pd.DataFrame([{'Status':'Pass', 'Value': '0'}, {'Status':'Pass', 'Value': '1'}, {'Status':'FAIL', 'Value': '2'}])
# add background color green to all lines with status 'PASS'
df.to_csv('test.csv')
df.style.map(lambda x: 'background-color: green' if x == 'Pass' else '', subset=['Status'])

Solution

  • You can't export colors to a text/CSV file. Furthermore, you ran your command after to_csv, which wouldn't affect it if this was supported.

    You can export as xlsx by chaining the style.map to to_excel:

    (
        df.style.map(
            lambda x: 'background-color: green' if x == 'Pass' else '',
            subset=['Status'],
        ).to_excel('color_test.xlsx')
    )
    

    Output:

    enter image description here