Explore Courses Blog Tutorials Interview Questions
0 votes
in Data Science by (50.2k points)

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.

I tried the following:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame(range(5), columns=['a'])

In [3]: df['b'] = df['a'].apply(lambda x: '{0}'.format(x))

In [4]: df


   a                     b

0  0

1  1

2  2

3  3

4  4

but the url is just displayed as text.

I also tried using ipython HTML object:

In [5]: from IPython.display import HTML

In [6]: df['b'] = df['a'].apply(lambda x:HTML('{0}'.format(x)))

In [7]: df


   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.

Any other ideas?

1 Answer

0 votes
by (108k points)

For representing the whole pandas object as Html object, refer the following code:

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="{0}">link</a>'.format(x))

In [4]: HTML(df.to_html(escape=False))

For  more info, refer the following code:

Browse Categories