Skip to content

ENH: Issue #2679. DataFrame.to_html() to create hyperlinks for valid URL... #9880

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pandas/core/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from pandas.core.base import PandasObject
from pandas.core.common import adjoin, notnull
from pandas.io.common import _is_url
from pandas.core.index import Index, MultiIndex, _ensure_index
from pandas import compat
from pandas.compat import(StringIO, lzip, range, map, zip, reduce, u,
Expand Down Expand Up @@ -861,8 +862,13 @@ def write_tr(self, line, indent=0, indent_delta=4, header=False,
self.write('<tr style="text-align: %s;">' % align, indent)
indent += indent_delta


for i, s in enumerate(line):
val_tag = tags.get(i, None)
if s and hasattr(s, 'lower'):
s = s.lstrip(' ')
if _is_url(s):
s = "<a href=\"%s\">%s</a>"%(s, s)
if header or (self.bold_rows and i < nindex_levels):
self.write_th(s, indent, tags=val_tag)
else:
Expand Down
29 changes: 29 additions & 0 deletions pandas/tests/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,35 @@ def test_to_html_multiindex_sparsify_false_multi_sparse(self):
</table>"""
self.assertEqual(result, expected)


def test_to_html_with_hyperlinks(self):
df = DataFrame([[0,'http://pandas.pydata.org/', 'pydata.org']],columns=['foo', 'bar', None], index=lrange(1))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add the issue number here as a comment

f = lambda x: 'a'[x]
result = df.to_html(formatters={'__index__': f})
#result = df.to_html()
expected = """\
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>foo</th>
<th>bar</th>
<th>None</th>
</tr>
</thead>
<tbody>
<tr>
<th>a</th>
<td>0</td>
<td>&lt;a href="http://pandas.pydata.org/"&gt;http://pandas.pydata.org/&lt;/a&gt;</td>
<td>pydata.org</td>
</tr>
</tbody>
</table>"""
self.assertEqual(result, expected)



def test_to_html_multiindex_sparsify(self):
index = MultiIndex.from_arrays([[0, 0, 1, 1], [0, 1, 0, 1]],
names=['foo', None])
Expand Down