Home > OS >  Add hyperlinks to pandas Styler table depending on index and column of each cell
Add hyperlinks to pandas Styler table depending on index and column of each cell

Time:06-30

I have a dataframe like

foo bar
Germany 1.0 2.0
England 3.0 4.0
France 5.0 6.0

and I want to save it to an html file using Styler.to_html() with clickable links on each cell number. Each hyperlink should be dependant on its corresponding index and column. For example clicking 1.0 should open a URL like http://example.com/foo/Germany.html.

I came across this question but it appears like using Styler.format does not allow me to access the corresponding index and column of the cell to be formatted so it's not possible to embed those into the hyperlink.

How can something like this be achieved?

CodePudding user response:

The styler.format method takes a cell value and can restructure it, including formatting it into a hyperlink.

Suppose your cell value was "w;v", then "<a x={0}>{1}".format(cell_value.split(";")) would return "<a x=w>v".

The trick in your case is pre-preparing the dataframe with the data in a necessary format before it is passed to Styler such that the styler element -by- element style formatting method can be applied as above.

  • Related