pandas 如何在熊猫中同时突出显示一行和一列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40335140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to highlight both a row and a column at once in pandas
提问by maxymoo
I can highlight a column using the syntax
我可以使用语法突出显示一列
import pandas as pd
df = pd.DataFrame([[1,0],[0,1]])
df.style.apply(lambda x: ['background: lightblue' if x.name == 0 else '' for i in x])
Similarly I can highlight a row by passing axis=1
:
同样,我可以通过传递突出显示一行axis=1
:
df.style.apply(lambda x: ['background: lightgreen' if x.name == 0 else '' for i in x],
axis=1)
However I can't work out how to do both at once; the problem is that when I use applymap
, I only get the values, not the names of the series that they come from.
但是我不知道如何同时做这件事;问题是,当我使用 时applymap
,我只得到值,而不是它们来自的系列的名称。
采纳答案by Psidom
How about doing something like this? Enumerate the column and check the index while building up the style list:
做这样的事情怎么样?枚举列并在构建样式列表时检查索引:
df.style.apply(lambda x: ['background: lightblue' if x.name == 0 or i == 0 else ''
for i,_ in x.iteritems()])
Or if you have color preference:
或者,如果您有颜色偏好:
df.style.apply(lambda x: [('background: lightblue' if x.name == 0
else ('background: lightgreen' if i == 0 else ''))
for i,_ in x.iteritems()])
回答by Iman Mirzadeh
You can also chain your styles:
您还可以链接您的样式:
import pandas as pd
df = pd.DataFrame([[1,0],[0,1]])
df.style\
.apply(lambda x: ['background: lightblue' if x.name == 0 else '' for i in x])\
.apply(lambda x: ['background: lightgreen' if x.name == 0 else '' for i in x], axis=1)