首页  >  文章  >  后端开发  >  如何在 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删除