首頁  >  文章  >  後端開發  >  如何在 pandas 中給定行索引和列名稱的特定單元格上色?

如何在 pandas 中給定行索引和列名稱的特定單元格上色?

WBOY
WBOY轉載
2024-02-15 16:39:03715瀏覽

如何在 pandas 中给定行索引和列名称的特定单元格上色?

問題內容

我有一個形狀為 (100,10) 的資料框 df 和每行的字典 columns_to_color 。

columns_to_color = {
  0: ['col1', 'col2', 'col9'],  # Columns 1, 2 and 9 should be colored for row 0
  1: ['col1', 'col5', 'col8'],  # Columns 1, 5 and 8 should be colored for row 1
  2: ['col3', 'col4', 'col7'],  # Columns 3, 4 and 7 should be colored for row 2
  .......

如何為該列的每一行的特定單元格著色?然後儲存到excel?


正確答案


您可以使用。 style.apply() 像這樣:

df.style.apply(
    lambda row: [
        'font-weight: bold' if col in columns_to_color[row.name] else ''
        for col in row.index],
    axis=1)

(我使用粗體只是為了方便。)

然後要轉換為 excel,請使用 .to_excel()

範例:

df = pd.DataFrame({f'col{n}': range(10*n, 10*n + 3) for n in range(10)})

apply 之後(在我的 ide 中):

以上是如何在 pandas 中給定行索引和列名稱的特定單元格上色?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除