Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save pandas to excel with different colors

I have a dataframe

df = pd.DataFrame(columns = ['id', 'name', 'age'])
df.loc[len(df), :] = [1, 'John', 21]
df.loc[len(df), :] = [2, 'Mary', 19]
df.loc[len(df), :] = [3, 'Ann', 27]
df.loc[len(df), :] = [4, 'Ben', 18]

I want to save it to excel file using xlsxwriter.

However, I want the age larger than 20 to be in red.

In other words, 21 and 27 should appear red in the excel file.

How to do it?

like image 575
Chan Avatar asked Jan 09 '19 11:01

Chan


People also ask

How do I save pandas data to Excel?

You can write any data (lists, strings, numbers etc) to Excel, by first converting it into a Pandas DataFrame and then writing the DataFrame to Excel. To export a Pandas DataFrame as an Excel file (extension: . xlsx, . xls), use the to_excel() method.

How do you conditional format in Excel using Python?

Practical Data Science using Python Excel uses conditional formatting to change the appearance of cells in a range based on user defined criteria. From the conditional formatting menu, it is possible to define criteria involving various types of values. In the worksheet shown below, the column A has different numbers.

How do I add conditional formatting to pandas?

One way to conditionally format your Pandas DataFrame is to highlight cells which meet certain conditions. To do so, we can write a simple function and pass that function into the Styler object using . apply() or .


1 Answers

You could use a conditional format with xlsxwriter like this:

import pandas as pd

# Create a Pandas dataframe from some data.
df = pd.DataFrame(columns = ['id', 'name', 'age'])
df.loc[len(df), :] = [1, 'John', 21]
df.loc[len(df), :] = [2, 'Mary', 19]
df.loc[len(df), :] = [3, 'Ann', 27]
df.loc[len(df), :] = [4, 'Ben', 18]

# 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']


# Add a format. Light red fill with dark red text.
format1 = workbook.add_format({'bg_color': '#FFC7CE',
                               'font_color': '#9C0006'})

# Set the conditional format range.
start_row = 1
start_col = 3
end_row = len(df)
end_cold = start_col

# Apply a conditional format to the cell range.
worksheet.conditional_format(start_row, start_col, end_row, end_cold,
                             {'type':     'cell',
                              'criteria': '>',
                              'value':    20,
                              'format':   format1})

# Close the Pandas Excel writer and output the Excel file.
writer.save()

Output:

output image

like image 170
jmcnamara Avatar answered Sep 30 '22 04:09

jmcnamara