【问题标题】:Styling Pandas dataframe within streamlit在 streamlit 中设置 Pandas 数据框的样式
【发布时间】:2023-01-20 11:44:08
【问题描述】:

我希望根据两个功能创建自己的样式条件:我想要背景颜色和大小 row_height 。

为此,我定义了 2 个样式函数

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 永远不会为空行更改并且似乎不起作用(没有错误消息)。当我采用任意非空条件或尝试将每个行高调整为 1px 时,情况也是如此。

streamlit 或我的代码有问题吗?

感谢帮助

【问题讨论】:

  • 你能分享一个更完整的代码sn-p吗?

标签: python pandas styles streamlit


【解决方案1】:

根据documentation for pd.style.apply,样式函数需要返回实际数据而不仅仅是格式化指令。

func - 函数

func 应该在 [0,1] 中获取一个 Series if axis 并返回一个相同长度的类似列表的对象,或者一个 Series,不一定具有相同的长度, 具有考虑子集的有效索引标签。 func 应该采取 DataFrame 如果 axis 为 None 并返回具有相同的 ndarray shape 或 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;")

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2014-10-08
    • 2021-01-07
    相关资源
    最近更新 更多