【发布时间】:2017-07-04 23:22:12
【问题描述】:
print('http://google.com') 输出一个可点击的 url。
如何获取pd.DataFrame(['http://google.com', 'http://duckduckgo.com']) 的可点击网址?
【问题讨论】:
print('http://google.com') 输出一个可点击的 url。
如何获取pd.DataFrame(['http://google.com', 'http://duckduckgo.com']) 的可点击网址?
【问题讨论】:
为此尝试使用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)
我希望这证明有用。
【讨论】:
'<a href="{0}">{0}</a>'.format(val)
apply.. 添加列,然后只需df.style 就足够了
f"<a href="{val}">{val}</a>"
如果您只想将 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:不幸的是,我没有足够的声望来评论@Abdou 的帖子)
【讨论】:
df['nameurl'] = df['name'] + '#' + df['url'], def make_clickable_both(val): name, url = val.split('#'), return f'<a href="{url}">{name}</a>', df.style.format({'nameurl': make_clickable_both})
new_df = df[['nameurl']] 创建一个只有nameurl 列的数据框。
@shantanuo :没有足够的声誉来发表评论。 下面的呢?
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)
【讨论】:
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)))
【讨论】: