Python Pandas 样式功能突出显示特定列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41654949/
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
Pandas style function to highlight specific columns
提问by Maria Petrova
I have been trying to write a function to use with pandas style. I want to highlight columns that I specify in the arguments. This is not very elegant, but, for example:
我一直在尝试编写一个用于熊猫风格的函数。我想突出显示我在参数中指定的列。这不是很优雅,但是,例如:
data = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
def highlight_cols(df, cols, colcolor = 'gray'):
for col in cols:
for dfcol in df.columns:
if col == cols:
color = colcolor
return ['background-color: %s' % color]*df.shape[0]
then call with:
然后调用:
data.style.apply(highlight_cols(cols=['B','C']))
I get an error: ("'Series' object has no attribute 'columns'")
我收到一个错误:(“'Series' 对象没有属性 'columns'”)
I think I fundamentally don't quite understand how the styler calls and applies the function.
我想我从根本上不太了解样式器如何调用和应用该函数。
Thanks,
谢谢,
回答by jezrael
I think you can use Slicing in Styles
for select columns B
and C
and then Styler.applymap
for elementwise styles.
我想你可以使用在切片Styles
的选择列B
,并C
再Styler.applymap
为按元素的风格。
import pandas as pd
import numpy as np
data = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
#print (data)
def highlight_cols(s):
color = 'grey'
return 'background-color: %s' % color
data.style.applymap(highlight_cols, subset=pd.IndexSlice[:, ['B', 'C']])
If you want more colors or be more flexible, use Styler.apply(func, axis=None)
, the function must return a DataFrame
with the same index and column labels:
如果您想要更多颜色或更灵活,请使用Styler.apply(func, axis=None)
,该函数必须返回DataFrame
具有相同索引和列标签的 a:
import pandas as pd
import numpy as np
data = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
#print (data)
def highlight_cols(x):
#copy df to new - original data are not changed
df = x.copy()
#select all values to default value - red color
df.loc[:,:] = 'background-color: red'
#overwrite values grey color
df[['B','C']] = 'background-color: grey'
#return color df
return df
data.style.apply(highlight_cols, axis=None)
回答by MaxU
You can do it bit more dynamically:
您可以更动态地执行此操作:
data = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
# dictionary of column colors
coldict = {'A':'grey', 'C':'yellow'}
def highlight_cols(s, coldict):
if s.name in coldict.keys():
return ['background-color: {}'.format(coldict[s.name])] * len(s)
return [''] * len(s)
data.style.apply(highlight_cols, coldict=coldict)