2

I have a dataframe df

df
Out[15]: 
           Subject ID  
StartDate                                                                    
2017-11-06        ID1  
2017-11-07        ID1
2017-11-08        ID2  
2017-11-10        ID3  

and I save it in an excel file

writer = pd.ExcelWriter(os.path.join(folders_path,'summary.xls'))
df.to_excel(writer,'Sheet1')
writer.save() 

However I would like to format the color of the rows according to the Subject ID , i.e. I would like a different colour for each ID

1 Answer 1

7

You have to use the 'xlsxwriter' engine and define your formats.

Below is a snippet of what is possible:

#!/usr/bin/env python3

from datetime import date
import pandas as pd

data = [['2017-11-06', 'ID1'],
        ['2017-11-07', 'ID1'],
        ['2017-11-08', 'ID2'],
        ['2017-11-10', 'ID3']]

df = pd.DataFrame(data, columns=['StartDate', 'Subject ID'])
print(df)

writer = pd.ExcelWriter('/home/spomared/tmp/summary.xls', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)

workbook = writer.book
worksheet = writer.sheets['Sheet1']

my_formats = {'"ID1"': '#FF0000',
              '"ID2"': '#00FF00',
              '"ID3"': '#0000FF'}

for val, color in my_formats.items():
    fmt = workbook.add_format({'font_color': color})
    worksheet.conditional_format('B2:B5', {'type': 'cell',
                                           'criteria': '=',
                                           'value': val,
                                           'format': fmt})

writer.save()

Here is the output Excel file:

enter image description here

You can find some references of conditional formatting on http://xlsxwriter.readthedocs.io/working_with_conditional_formats.html

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! I wanted to color all the rows (background).. not only the "IDs"...is that possible?
Of course: just change the font_color keyword by bg_color in workbook.add_format. Consider looking at the given xlsxwriter link: it shows lots of use cases.
See the format help page to have a list of available options: xlsxwriter.readthedocs.io/format.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.