Insert a link inside a Pandas table

2024/11/19 13:23:16

I'd like to insert a link (to a web page) inside a Pandas table, so when it is displayed in an IPython notebook, I could press the link.

I tried the following:

In [1]: import pandas as pdIn [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

But the URL is just displayed as text.

I also tried using an IPython HTML object:

In [5]: from IPython.display import HTMLIn [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.

Any other ideas?


alko got the right answer. I just wanted to add that the cell width is limited by default, and long HTML code will be truncated, i.e.:

<a href="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0">xxx</a>

will become this:

<a href="aaaaaaaaaaaaaaaaaaaaaa...

and won't be displayed correctly. (Even though the text xxx is short and can fit in the cell.)

I've bypassed it by setting:

pd.set_printoptions(max_colwidth=-1)
Answer

I suppose you have to represent whole Pandas object as an HTML object, that is

In [1]: from IPython.display import HTMLIn [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))

Sorry, now I don't have IPython at hand, and can't check whether the output is correct.

https://en.xdnf.cn/q/26434.html

Related Q&A

TypeError: string indices must be integers while parsing JSON using Python?

I am confuse now why I am not able to parse this JSON string. Similar code works fine on other JSON string but not on this one - I am trying to parse JSON String and extract script from the JSON.Below …

Python dynamic inheritance: How to choose base class upon instance creation?

IntroductionI have encountered an interesting case in my programming job that requires me to implement a mechanism of dynamic class inheritance in python. What I mean when using the term "dynamic …

Python: efficiently check if integer is within *many* ranges

I am working on a postage application which is required to check an integer postcode against a number of postcode ranges, and return a different code based on which range the postcode matches against.E…

How to pass on argparse argument to function as kwargs?

I have a class defined as followsclass M(object):def __init__(self, **kwargs):...do_somethingand I have the result of argparse.parse_args(), for example:> args = parse_args() > print args Namespa…

How do you check whether a python method is bound or not?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that its bound to?

Most Pythonic way to declare an abstract class property

Assume youre writing an abstract class and one or more of its non-abstract class methods require the concrete class to have a specific class attribute; e.g., if instances of each concrete class can be …

PyQt on Android

Im working on PyQt now, and I have to create the application on Android, Ive seen the kivy library, but its too crude.Is there any way now to run an application on Android made on PyQt?

How to elementwise-multiply a scipy.sparse matrix by a broadcasted dense 1d array?

Suppose I have a 2d sparse array. In my real usecase both the number of rows and columns are much bigger (say 20000 and 50000) hence it cannot fit in memory when a dense representation is used:>>…

Do I have to do StringIO.close()?

Some code:import cStringIOdef f():buffer = cStringIO.StringIO()buffer.write(something)return buffer.getvalue()The documentation says:StringIO.close(): Free the memory buffer. Attempting to do furtherop…

Python: ulimit and nice for subprocess.call / subprocess.Popen?

I need to limit the amount of time and cpu taken by external command line apps I spawn from a python process using subprocess.call , mainly because sometimes the spawned process gets stuck and pins the…