执行代码后,转置列中的多个条目将有条件地突出显示。
我只想突出显示每个转置列中的顶部值和底部值。
以下是参考代码:
import pandas as pd
import streamlit as st
# Sample DataFrame
data = {
'E0': ["Header1", "Header2", "Header3", "Header4"],
'E1': [10, 20, 3, 5],
'E2': [25, None, 20, 1],
'E3': [5, 10, 8, None]
}
df = pd.DataFrame(data)
df_transposed = df.transpose()
custom_text = 'Not Available'
df_filled = df_transposed.fillna(custom_text)
def highlight_top(val):
if val == df_transposed.loc['E1'].max() or val == df_transposed.loc['E2'].max() or val == df_transposed.loc['E3'].max():
return 'background-color: green; color: white;'
else:
return ''
def highlight_bot(val):
if val == df_transposed.loc['E1'].min() or val == df_transposed.loc['E2'].min() or val == df_transposed.loc['E3'].min():
return 'background-color: red; color: white;'
else:
return ''
# Applying the style to the transposed DataFrame
styled_df = df_filled.style.applymap(highlight_top).applymap(highlight_bot)
st.table(styled_df)
describe
来获取 min
/max
,然后使用 apply
预定义的 CSS 样式:
CSS = "background-color:{bc}; color:{c}" # add more if needed
STATS = {"min": {"stat": "min", "bg": "red", "c": "white"},
"max": {"stat": "max", "bg": "green", "c": "white"}}
def highlight_mm(df_tos, stat, bg, c):
# global df
import numpy as np
desc = df.drop(columns="E0").describe()
mask = df_tos.eq(desc.loc[stat], axis=0)
return np.where(mask, CSS.format(bc=bg, c=c), "")
styled_df = (
df_filled.style
.apply(highlight_mm, **STATS["min"], axis=None)
.apply(highlight_mm, **STATS["max"], axis=None)
.format(precision=2) # this one is optional
)
st.table(styled_df)
输出(在 Streamlit):