【问题标题】:How can I convert a column of strings into hyperlink?如何将一列字符串转换为超链接?
【发布时间】:2020-12-27 05:34:24
【问题描述】:

我想将链接列转换为超链接,以便在数据表上显示。

列链接如下所示:

    link
0   https://twitter.com/CertSG/status/1286557929198563328

1   https://twitter.com/osiseguridad/status/1286565901568016384

我正在考虑创建一个函数来使用<a href = "x" </a> 转换字符串超链接,其中x01 的值等等。我也认为 for 可以帮助我实现它,但我真的不知道什么是更好的方法

type(df.link)pandas.core.series.Series 我正在使用熊猫 3.8.5

我希望我的表格在表格中添加链接https://plotly.com/python/figure-factory-table/

非常感谢,我是新手

【问题讨论】:

  • 你尝试了什么? df.apply(your_function) 怎么样?
  • 没有pandas 3.8.5,但有Python 3.8.5pandas 1.1.0
  • 是的,你是对的。我对这个 python 世界很陌生,所以我犯了一个错误

标签: python string dataframe hyperlink


【解决方案1】:

您可以使用df.apply(convert, axis=1) 在每一行上运行自己的函数convert()

import pandas as pd

df = pd.DataFrame({
    'link': [
        'https://twitter.com/CertSG/status/1286557929198563328',
        'https://twitter.com/osiseguridad/status/1286565901568016384'
    ]
})

def convert(row):
    #print(row)
    return '<a href="{}">{}</a>'.format(row['link'],  row.name)

df['link'] = df.apply(convert, axis=1)

print(df)

# Display it with `plotly`

import plotly.figure_factory as ff

fig = ff.create_table(df)
fig.show()

编辑:直接显示在streamlit

import pandas as pd

df = pd.DataFrame({
    'link': [
        'https://twitter.com/CertSG/status/1286557929198563328',
        'https://twitter.com/osiseguridad/status/1286565901568016384'
    ]
})

def convert(row):
    #print(row)
    return '<a href="{}">{}</a>'.format(row['link'],  row.name)

df['link'] = df.apply(convert, axis=1)

print(df)

import streamlit as st

st.write(df.to_html(escape=False), unsafe_allow_html=True)

【讨论】:

  • 嗨弗拉斯!谢谢你的回答,我真的很喜欢你这样做的方式,因为我正在考虑做这样的事情,但我希望输出是一个超链接,这样仍然会返回一个字符串
  • pandas 中总是字符串。只有当你用浏览器中显示的工具显示时才可以是超链接,它可以把它当作超链接。
  • 我在代码中添加了plotly.figure_factory,它显示了带有超链接的网页。
  • 我在 streamlit 上显示它但它不起作用:c
  • 你没有提到streamlit,但你显示了plotly。你如何显示它?您是否生成 HTML 并发送到模板?如果它像 Flask 一样工作,那么它可能需要选项 safe 将其视为 HTML - {{ html | safe }}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-03
  • 1970-01-01
  • 1970-01-01
  • 2018-02-15
相关资源
最近更新 更多