pandas 样式功能突出显示特定列 [英] Pandas style function to highlight specific columns
问题描述
我一直在尝试编写一个用于熊猫风格的函数.我想突出显示我在参数中指定的列.这不是很优雅,但是,例如:
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]
然后致电:
data.style.apply(highlight_cols(cols=['B','C']))
我得到一个错误: (系列"对象没有属性列"")
I get an error: ("'Series' object has no attribute 'columns'")
我认为我从根本上不了解样式器如何调用和应用该函数.
I think I fundamentally don't quite understand how the styler calls and applies the function.
谢谢
推荐答案
I think you can use Slicing in Styles
for select columns B
and C
and then Styler.applymap
for elementwise styles.
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']])
如果要更多颜色或更灵活,请使用Styler.apply(func, axis=None)
,该函数必须返回具有相同索引和列标签的DataFrame
:
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:
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)
这篇关于 pandas 样式功能突出显示特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!