如何使用字典设置Python Pandas Dataframe的样式 [英] How to style a Python Pandas Dataframe using dictionary
本文介绍了如何使用字典设置Python Pandas Dataframe的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下索引为"NUM"的熊猫数据框:
I have the following pandas dataframe with index "NUM":
我想使用以下字典添加颜色到单元格:
I want to add color to cells using the followin dictionary:
d = {'R1': [1,2,3,4,5,6,7,8,9,10]
,'R2': [3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
,'R3': [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]
,'R4': [11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]
,'R5': [17,18,19,20,21,22,23,24,25,26,27,28]
}
字典值(列表)中的值是数据框中的索引.我想将背景色添加到单元格中,例如在"R1"列颜色1到10,在"R2"中列颜色3到20等.
The values in the dictionary values (lists) are the index in the dataframe. I want to add background color to the cells, for example in "R1" column color 1 to 10, in "R2" column color 3 to 20 and so on.
谢谢
推荐答案
您可以尝试:
df.style.apply(
lambda x: ['background-color:red' if i in d[x.name] else ''
for i in np.arange(len(x))+1]
)
输出:
这篇关于如何使用字典设置Python Pandas Dataframe的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文