python 如何在Pandas和木星笔记本中创建带有可点击超链接的表格

vlju58qv  于 2022-10-30  发布在  Python
关注(0)|答案(5)|浏览(151)

print('http://google.com')输出一个可点击的url。
如何获取pd.DataFrame(['http://google.com', 'http://duckduckgo.com'])的可点击URL?

hc8w905p

hc8w905p1#

如果您只想将URL格式套用至单一栏,可以用途:

data = [dict(name='Google', url='http://www.google.com'),
        dict(name='Stackoverflow', url='http://stackoverflow.com')]
df = pd.DataFrame(data)

def make_clickable(val):
    # target _blank to open new window
    return '<a target="_blank" href="{}">{}</a>'.format(val, val)

df.style.format({'url': make_clickable})

(PS:很遗憾,我没有足够的声望把这个作为评论发到@阿卜杜的帖子上)

yb3bgrhw

yb3bgrhw2#

请尝试使用pd.DataFrame.style.format执行以下操作:

df = pd.DataFrame(['http://google.com', 'http://duckduckgo.com'])

def make_clickable(val):
    return '<a href="{}">{}</a>'.format(val,val)

df.style.format(make_clickable)

我希望这证明有用。

qpgpyjmq

qpgpyjmq3#

@山塔诺:没有足够的声誉来评论。下面怎么样?

def make_clickable(url, name):
    return '<a href="{}" rel="noopener noreferrer" target="_blank">{}</a>'.format(url,name)

df['name'] = df.apply(lambda x: make_clickable(x['url'], x['name']), axis=1)
sxissh06

sxissh064#

from IPython.core.display import display, HTML
import pandas as pd

# create a table with a url column

df = pd.DataFrame({"url": ["http://google.com", "http://duckduckgo.com"]})

# create the column clickable_url based on the url column

df["clickable_url"] = df.apply(lambda row: "<a href='{}' target='_blank'>{}</a>".format(row.url, row.url.split("/")[2]), axis=1)

# display the table as HTML. Note, only the clickable_url is being selected here

display(HTML(df[["clickable_url"]].to_html(escape=False)))
iecba09b

iecba09b5#

我在How to Create a Clickable Link(s) in Pandas DataFrame and JupyterLab找到了这个,它解决了我的问题:

HTML(df.to_html(render_links=True, escape=False))

相关问题