[英]Styling Pandas dataframe within streamlit
我希望根據兩個函數創建自己的樣式條件:我想要背景顏色和大小 row_height。
為此,我定義了 2 個 styles 函數
def resistance(s):
color='#fcdcdc' if s.interpretation=='Resistant' else ''
return ['background-color: {}'.format(color)]*len(s)
def null_row(s):
size=1px if s.interpretation=='' else size=12px
return ['line-height: {}'.format(color)]*len(s)
df_style=df.style.\
apply(resistance,axis=1).\
apply(height,axis=1)
st.table(df_style)
st.dataframe(df_style)
除了 line_height 永遠不會為空行更改並且似乎不起作用(沒有錯誤消息)。 當我采用任意非 null 條件或嘗試將每個行高調整為 1px 時,情況相同。
streamlit 或我的代碼有問題嗎?
感謝幫助
根據 pd.style.apply 的文檔,樣式 function 需要返回實際數據,而不僅僅是格式化指令。
功能 - function
如果軸在 [0,1] 中,func 應該采用一個系列,並返回一個長度相同的類似列表 object,或者一個系列,不一定具有相同的長度,並具有考慮子集的有效索引標簽。 如果 axis 為 None,func 應該采用 DataFrame 並返回具有相同形狀的 ndarray 或 DataFrame,不一定具有相同的形狀,具有考慮子集的有效索引和列標簽。
示例代碼是這樣的:
def highlight_max(x, color):
return np.where(x == np.nanmax(x.to_numpy()), f"color: {color};", None)
df = pd.DataFrame(np.random.randn(5, 2), columns=["A", "B"])
df.style.apply(highlight_max, color='red')
df.style.apply(highlight_max, color='blue', axis=1)
df.style.apply(highlight_max, color='green', axis=None)
您需要使您的功能適應您想要實現的目標並返回您實際想要格式化的數據。 如果我理解您想正確執行的操作,那么這應該是正確的代碼:
def resistance(s):
return np.where(s.interpretation=='Resistant', "background-color: '#fcdcdc';", None)
def null_row(s):
return np.where(s.interpretation=='', "line-height: 1px;", "line-height: 12px;")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.