我有一个形状为 (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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号