K.-Michael Aye
K.-Michael Aye

Reputation: 5605

dataframe.to_html does not create hyperlinks

The HTML file that comes out of Dataframe.to_html() does not create hyperlinks when the string content of one of its columns matches an URI.

Is there a way to generate hyperlinks in html docs from a DataFrame?

Upvotes: 2

Views: 3741

Answers (3)

Display name
Display name

Reputation: 926

Setting escape=False allows you to input custom html and create hyperlinks as demonstrated below.

df = pd.DataFrame(data)
df['url'] = '<a href=' + df['url'] + '><div>' + df['name'] + '</div></a>'
df = df.to_html(escape=False)

Upvotes: 3

Phil&#228; Bu
Phil&#228; Bu

Reputation: 105

Depends on how dynamic your links have to be. I'm currently working on the same issue and tried to solve it with jQuery:

$(document).ready(function(){
  $('thead th').each(function(){
    $(this).html('<a href="{% url "cat_view" %}">' + $(this).html() + '</a>');
  });
  $('tbody tr th').each(function(){
    $(this).html('<a href="{% url "date_view" %}">' + $(this).html() + '</a>')
  });
});

This makes the headers links, but you could just use it on $('tobdy tr td') if that's what you need. I currently have django url-template tags for the hrefs but you could basically put anything in there. I'm still struggling to correctly construct the href's as soon as they get dynamic (e.g. {% url 'cat_view' cat=category.pk %})

Upvotes: 0

dag
dag

Reputation: 451

I don't think so. The HTMLFormatter used by DataFrame.to_html helps to pretty render a DataFrame in a IPython HTML Notebooks I think.

The method does not parse each element of your DataFrame, i.e. recognizes an URI pattern to write <a href="URI">Content</a> or something else.

I don't think that (1) it's planned and (2) it's not the purpose of this method. Maybe you can add an issue to the GitHub pandas issues page.

Upvotes: 1

Related Questions