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

2024年 2月 15日 58.6k 0

如何在 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 中给定行索引和列名称的特定单元格上色?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论