在 pandas 表中插入链接 [英] Insert a link inside a pandas table
问题描述
我想在熊猫表中插入一个链接(到网页),所以当它显示在ipython笔记本中时,我可以按该链接.
I'd like to insert a link (to a web page) inside a pandas table, so when it is displayed in ipython notebook, I could press the link.
我尝试了以下操作:
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仅显示为文本.
but the url is just displayed as text.
我也尝试使用ipython HTML对象:
I also tried using ipython HTML object:
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>
,但只会显示对象的代表.
but it will only display the repr of the object.
还有其他想法吗?
alko得到了正确的答案,只是想补充一下,默认情况下,单元格的宽度是有限的,并且长的html代码将被截断,即:
alko got the right answer, just wanted to add that the cell width is limited by default, and long html code will be truncated, ie:
<a href="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0">xxx</a>
将变为:
<a href="aaaaaaaaaaaaaaaaaaaaaa...
,并且不会正确显示. (即使xxx文本很短并且可以在单元格中显示)
and won't be displayed correctly. (even though the text xxx is short and can fit in the cell)
我通过设置来绕过它:
pd.set_printoptions(max_colwidth=-1)
推荐答案
I suppose you have to represent whole pandas object as html object, that is
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,也无法检查输出是否正确.
Sorry, now don't have IPython at hand, and can't check whether output is correct.
这篇关于在 pandas 表中插入链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!