我想在 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 HTML 对象:
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。
还有其他想法吗?
alko 得到了正确的答案。我只是想补充一点,默认情况下单元格宽度是有限的,长HTML代码将被截断,即:
<a href="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0">xxx</a>
会变成这样:
<a href="aaaaaaaaaaaaaaaaaaaaaa...
并且不会正确显示。(即使文本 xxx 很短并且可以放入单元格中。)
我通过设置绕过它:
pd.set_printoptions(max_colwidth=-1)