Skip to content

Commit 8fc784b

Browse files
author
tdas
committed
ENH: Issue pandas-dev#2679. DataFrame.to_html() to create hyperlinks for valid URL strings
1 parent 35b20d8 commit 8fc784b

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

pandas/core/format.py

+6
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

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

865+
864866
for i, s in enumerate(line):
865867
val_tag = tags.get(i, None)
868+
if s and hasattr(s, 'lower'):
869+
s = s.lstrip(' ')
870+
if _is_url(s):
871+
s = "<a href=\"%s\">%s</a>"%(s, s)
866872
if header or (self.bold_rows and i < nindex_levels):
867873
self.write_th(s, indent, tags=val_tag)
868874
else:

pandas/tests/test_format.py

+29
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,35 @@ def test_to_html_multiindex_sparsify_false_multi_sparse(self):
716716
</table>"""
717717
self.assertEqual(result, expected)
718718

719+
720+
def test_to_html_with_hyperlinks(self):
721+
df = DataFrame([[0,'http://pandas.pydata.org/', 'pydata.org']],columns=['foo', 'bar', None], index=lrange(1))
722+
f = lambda x: 'a'[x]
723+
result = df.to_html(formatters={'__index__': f})
724+
#result = df.to_html()
725+
expected = """\
726+
<table border="1" class="dataframe">
727+
<thead>
728+
<tr style="text-align: right;">
729+
<th></th>
730+
<th>foo</th>
731+
<th>bar</th>
732+
<th>None</th>
733+
</tr>
734+
</thead>
735+
<tbody>
736+
<tr>
737+
<th>a</th>
738+
<td>0</td>
739+
<td>&lt;a href="http://pandas.pydata.org/"&gt;http://pandas.pydata.org/&lt;/a&gt;</td>
740+
<td>pydata.org</td>
741+
</tr>
742+
</tbody>
743+
</table>"""
744+
self.assertEqual(result, expected)
745+
746+
747+
719748
def test_to_html_multiindex_sparsify(self):
720749
index = MultiIndex.from_arrays([[0, 0, 1, 1], [0, 1, 0, 1]],
721750
names=['foo', None])

0 commit comments

Comments
 (0)