简体   繁体   English

熊猫数据框中的颜色列名称

[英]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: 经过不同的操作后,我在python中创建了一个高维数据框(df),其中的列名称如下所示:

  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". 因此,列名是不同的时间序列(Jan00,Feb01等。)和诸如“产品”,“服务”和“国家/地区”之类的单词。 I want to export this data frame to xlsx format and I would like to highlight these 3 words( Product, Service, Country). 我想将此数据框导出为xlsx格式,我想突出显示这3个字(产品,服务,国家/地区)。 This is the code which I used in order to export the output in excel: 这是我用来在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? 您能否建议我如何突出显示这3个列名称(用红色表示),以便在生成的excel电子表格中获得突出显示的格式? 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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