簡體   English   中英

熊貓數據框中的顏色列名稱

[英]Color column names in pandas data frame

經過不同的操作后,我在python中創建了一個高維數據框(df),其中的列名稱如下所示:

  Product   Jan00   Feb00    ..  ..  Dec00   Service   Jan01  Feb01  ..  Country  ..

    ..       ..      ..      ..  ..    ..      ..        ..      ..   ..    ..

    ..       ..      ..      ..  ..    ..      ..        ..      ..   ..    ..

因此,列名是不同的時間序列(Jan00,Feb01等。)和諸如“產品”,“服務”和“國家/地區”之類的單詞。 我想將此數據框導出為xlsx格式,我想突出顯示這3個字(產品,服務,國家/地區)。 這是我用來在excel中導出輸出的代碼:

output_doc = pd.ExcelWriter('Project.xlsx')

df.to_excel(output_doc, sheet_name = 'TEST', index = False)

output_doc.save()

您能否建議我如何突出顯示這3個列名稱(用紅色表示),以便在生成的excel電子表格中獲得突出顯示的格式? 提前致謝

首先,您需要創建突出顯示單元格的功能:

def func():
    #here contidions for  highlighting the cells
    return ['background-color: red']

現在,您可以將此功能應用於所需的單元格:

data_frame.style.apply(func)

第二種變體是:

# 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