Reputation: 1079
after different manipulations, I have created a high dimension data frame (df) in python where the column names are like this:
Product Jan00 Feb00 .. .. Dec00 Service Jan01 Feb01 .. Country ..
.. .. .. .. .. .. .. .. .. .. ..
.. .. .. .. .. .. .. .. .. .. ..
Therefore, the column names are differnt time series (Jan00, Feb01 etc..) and some words like "Product", "Service" and "Country". I want to export this data frame to xlsx format and I would like to highlight these 3 words( Product, Service, Country). This is the code which I used in order to export the output in excel:
output_doc = pd.ExcelWriter('Project.xlsx')
df.to_excel(output_doc, sheet_name = 'TEST', index = False)
output_doc.save()
Could you suggest how can I highlight these 3 column names (let's say with red color) in order to get the highlighted format in the generated excel spreadsheet? Thanks in advance
Upvotes: 1
Views: 5018
Reputation: 844
Firstly you need to create function which will highlighting your cells:
def func():
#here contidions for highlighting the cells
return ['background-color: red']
Now you can apply this function to cells you need:
data_frame.style.apply(func)
Second variant is:
# 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']
# Apply a conditional format to the cell range.
worksheet.conditional_format('B2:B8', {'type': '3_color_scale'})
# Close the Pandas Excel writer and output the Excel file.
writer.save()
Upvotes: 1