我想在一个Pandas表格中插入一个链接(到一个网页),这样当它显示在IPython笔记本中时,我就可以按下这个链接。
我尝试了以下几种方法:
In [1]: import pandas as pd
In [2]: df = pd.DataFrame(range(5), columns=['a'])
In [3]: df['b'] = df['a'].apply(lambda x: 'http://example.com/{0}'.format(x))
In [4]: df
Out[4]:
a b
0 0 http://example.com/0
1 1 http://example.com/1
2 2 http://example.com/2
3 3 http://example.com/3
4 4 http://example.com/4
但是URL只显示为文本。
我还尝试使用了一个IPython对象:
In [5]: from IPython.display import HTML
In [6]: df['b'] = df['a'].apply(lambda x:HTML('http://example.com/{0}'.format(x)))
In [7]: df
Out[7]:
a b
0 0 <IPython.core.display.HTML object at 0x0481E530>
1 1 <IPython.core.display.HTML object at 0x0481E770>
2 2 <IPython.core.display.HTML object at 0x0481E7B0>
3 3 <IPython.core.display.HTML object at 0x0481E810>
4 4 <IPython.core.display.HTML object at 0x0481EA70>
但它将只显示对象的repr。
还有其他想法吗?
阿尔科得到了正确的答案。我只想补充说,单元格的宽度在默认情况下是有限的,并且长的HTML代码将被截断,即:
<a href="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0">xxx</a>
将变成这样:
<a href="aaaaaaaaaaaaaaaaaaaaaa...
并且不会正确显示。(即使文本xxx很短并且可以放在单元格中。)
我通过设置以下内容绕过了它:
pd.set_printoptions(max_colwidth=-1)
发布于 2013-11-18 17:03:36
我认为您必须将整个Pandas对象表示为一个HTML object,即
In [1]: from IPython.display import HTML
In [2]: df = pd.DataFrame(list(range(5)), columns=['a'])
In [3]: df['a'] = df['a'].apply(lambda x: '<a href="http://example.com/{0}">link</a>'.format(x))
In [4]: HTML(df.to_html(escape=False))
对不起,我现在手头没有IPython,无法检查输出是否正确。
发布于 2020-08-04 22:02:38
如果您想避免缩短长urls的问题,您还可以显示具有唯一或标准值的链接。
df['Url'] = '<a href=' + df['Url'] + '><div>' + df['Name'] + '</div></a>'
df = df.to_html(escape=False)
# OR
df['Url'] = '<a href=' + df['Url'] + '><div>'Hello World'</div></a>'
df = df.to_html(escape=False)
发布于 2021-06-27 22:47:30
安装pretty-html-table
from pretty_html_table import build_table
body = """
<html>
<head>
</head>
<body>
{0}
</body>
</html>
""".format(build_table(df, 'blue_light'))
您不必担心DataFrame中网站链接的格式和格式,输出将只包含超链接。
https://stackoverflow.com/questions/20035518
复制相似问题