[英]Highligh the max and min value in a column pandas
如果使用1.3.0
以上的 pandas 版本,請使用:
(df.style.highlight_max(axis=0, props='background-color:green;', subset=['A','B'])
.highlight_min(axis=0, props='background-color:red;', subset=['A','B'])
.to_excel('styled.xlsx', engine='openpyxl'))
如果使用舊版本:
def highlight_min_max(x):
c1 = 'background-color: green'
c2 = 'background-color: red'
# condition
m1 = x.eq(x.max())
m2 = x.eq(x.min())
# empty DataFrame of styles
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
# set columns by conditions
return df1.mask(m1, c1).mask(m2, c2)
df.style.apply(highlight_min_max, axis=None, subset=['A','B'])
選擇:
def highlight_max(s, props=''):
return np.where(s == np.nanmax(s.values), props, '')
def highlight_min(s, props=''):
return np.where(s == np.nanmin(s.values), props, '')
(df.style.apply(highlight_max, axis=0, props='background-color:green;', subset=['A','B'])
.apply(highlight_min, axis=0, props='background-color:red;', subset=['A','B'])
.to_excel('styled.xlsx', engine='openpyxl'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.