简体   繁体   中英

Color column names in pandas data frame

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

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()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM