如何在Streamlit中实现DataFrame单元格的可点击超链接?
在Streamlit中展示带可点击超链接的DataFrame解决方案
问题场景
在Jupyter Notebook中可以正常生成带可点击超链接的DataFrame,但迁移到Streamlit时,使用st.dataframe(df.style.apply(...))会触发如下报错:
ValueError: Function <function at 0x0000028F008DC9D0> resulted in the apply method collapsing to a Series. Usually, this is the result of the function returning a single value, instead of list-like.
报错原因
- Streamlit的
st.dataframe对Pandas Styler对象的支持有限,且默认不渲染HTML内容; style.apply(axis=1)要求函数返回与行长度匹配的列表型结果,但你的lambda仅返回单个字符串,导致结果坍缩为Series,不符合方法要求。
解决方法
直接生成包含HTML链接的列,通过st.markdown渲染成可点击的表格,这是最可靠的实现方式:
import pandas as pd import streamlit as st df = pd.DataFrame({ 'name': ['stackoverflow', 'gis stackexchange', 'meta stackexchange'], 'url': ['https://stackoverflow.com', 'https://gis.stackexchange.com/', 'https://meta.stackexchange.com'] }) def make_clickable(url, name): return f'<a href="{url}" rel="noopener noreferrer" target="_blank">{name}</a>' # 生成带HTML超链接的列 df['link'] = df.apply(lambda x: make_clickable(x['url'], x['name']), axis=1) # 将DataFrame转为HTML表格,并用st.markdown渲染(关闭HTML转义) st.markdown(df[['link']].to_html(escape=False), unsafe_allow_html=True)
补充说明
如果需要保留原有的name和url列,只需调整to_html时选择的列即可:
# 保留name、url和link列 st.markdown(df.to_html(escape=False), unsafe_allow_html=True)
内容的提问来源于stack exchange,提问作者Timeless
相关产品推荐
相关产品推荐

