0

I have created a data Frame which has a column Status. This column can have two values - Success and Failed. I want to fill color to all rows in this column with value Failed.

Please help me to implement this?

example: Sample dataframe is given below:

Master Job Name   Status

Settlement_limit  Success
Settlement_Trans  **Failed**
Ix_rm_bridge      Success
Unit_test         **Failed**
Shijith
  • 4,602
  • 2
  • 20
  • 34
ashmita
  • 39
  • 6

1 Answers1

0

u can use Styler.applymap to apply style functions elementwise

import pandas as pd
data = {'Master Job Name':['Settlement_limit', 'Settlement_Trans', 'Ix_rm_bridge', 'Unit_test'], 
        'Status':['Success', 'Failed', 'Success', 'Failed']} 

df = pd.DataFrame(data)

# function to fill font color
def fill_color(val):
    return 'color: red' if val=='Failed' else ''

df = df.style.applymap(fill_color, subset=['Status'])
df.to_excel('mysheet.xlsx') # excel sheet will be saved to present working directory, open the excel sheet to view changes

enter image description here

Shijith
  • 4,602
  • 2
  • 20
  • 34
  • Thanks for the answer. If i want to fill red color in whole cell then what to do? – ashmita Nov 27 '19 at 08:58
  • change the return value in the function to `'background-color: red' if val=='Failed' else ''` – Shijith Nov 27 '19 at 09:01
  • i am running this code in sublime text. while running its not reflecting the color. – ashmita Nov 27 '19 at 09:04
  • if you want to view the changes run the code in a jupyter notebook, oterwise save to an excel sheet (updated the code ) – Shijith Nov 27 '19 at 09:15
  • i saved the dataframe in csv file. But red color is still not showing. – ashmita Nov 27 '19 at 12:30
  • a `csv` is a comma seperated `text` file, you cannot save styles to a `csv`, you have to save to an excel file(extension `.xlsx` or `.xls`), then only you can view styles. – Shijith Nov 27 '19 at 12:37
  • to save a dataframe to excel with `.xlsx` extension pandas need either `xlsxwriter` or `openpyxl` library , so check if its available, otherwise install one of those, using `pip install openpyxl` , if you are using anaconda do `conda install -c anaconda openpyxl` – Shijith Nov 27 '19 at 12:47
  • i saved dataframe in .xlsx extension but still background color is not showing. – ashmita Nov 27 '19 at 12:51
  • did you save back to df , `df = df.style.applymap(fill_color, subset=['Status'])`? copy paste the above code and see if its working. it should work – Shijith Nov 27 '19 at 12:54
  • Thanks.. Now its working. – ashmita Nov 27 '19 at 12:58