I am exporting to Excel two pandas DataFrames
using XlsxWriter, each DataFrame
having a separate sheet. I would like to apply a colour format to all the cells in one sheet based on values in another sheet, they correspond one-to-one based on column names and row numbers.
Example:
Sheet1
A B C
1 1 3 1
2 0 4 2
Sheet2
A B C
1 a d b
2 b a a
I would like to assign a colour format to all the cells in Sheet1 that have a value 'a' in Sheet2.
The first step is to work out the conditional format in Excel and then transfer it to XlsxWriter.
Something like the following should work:
import pandas as pd
# Create some Pandas dataframes from some data.
df1 = pd.DataFrame([[ 1, 3, 1 ], [ 0, 4, 2 ]])
df2 = pd.DataFrame([['a', 'd', 'b'], ['b', 'a', 'a']])
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_xlsxwriter.xlsx', engine='xlsxwriter')
# Write each dataframe to a different worksheet.
df1.to_excel(writer, sheet_name='Sheet1', header=False, index=False)
df2.to_excel(writer, sheet_name='Sheet2', header=False, index=False)
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Create a format for the conditional format.
condition_format = workbook.add_format({'bg_color': '#C6EFCE',
'font_color': '#006100'})
# Write a conditional format over a range.
worksheet.conditional_format('A1:C2', {'type': 'formula',
'criteria': '=Sheet2!A1="a"',
'format': condition_format})
# Close the Pandas Excel writer and output the Excel file.
writer.save()
Output:
Note that Excel requires double quotes around the string in the formula =Sheet2!A1="a"
and by using a relative cell reference ( A1
not the absolute value $A$1
) the formula is applied individually to each cell in the range.
You can apply the conditional format to a range based on the dataframe like this:
# Write a conditional format over a range.
start_row = 0
start_col = 0
end_row = df1.shape[0] -1
end_col = df1.shape[1] -1
worksheet.conditional_format(start_row, start_col, end_row, end_col,
{'type': 'formula',
'criteria': '=Sheet2!A1="a"',
'format': condition_format})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.