-
Notifications
You must be signed in to change notification settings - Fork 19
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Wrap DataFrames in order to allow custom styling (closes #76)
- Loading branch information
Showing
3 changed files
with
38 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
import re | ||
|
||
import pandas as pd | ||
|
||
|
||
class StylizedDataFrame(pd.DataFrame): | ||
def _make_urls_clickable(self, val): | ||
if isinstance(val, str) and re.search("^https?://", val): | ||
return f'<a target="_blank" href="{val}">{val}</a>' | ||
else: | ||
return val | ||
|
||
def to_html(self, *args, **kwargs): | ||
styler = self.style.format(self._make_urls_clickable) | ||
return styler.render(*args, **kwargs) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
from arche.tools.dataframe import StylizedDataFrame | ||
import pandas as pd | ||
|
||
|
||
def test_stylized_df_make_urls_clickable(): | ||
data = {"col1": [1, 2], "col2": ["http://foo.com", "https://bar.com"]} | ||
df1 = pd.DataFrame(data) | ||
assert "<a href=" not in df1.to_html() | ||
|
||
html = StylizedDataFrame(df1).to_html() | ||
assert '<a target="_blank" href="http://foo.com">http://foo.com</a>' in html | ||
assert '<a target="_blank" href="https://bar.com">https://bar.com</a>' in html | ||
|
||
|
||
def test_stylized_df_does_not_add_links_if_no_url_found(): | ||
data = {"col1": [1, 2], "col2": ["foo", "bar"]} | ||
html = pd.DataFrame(data).to_html() | ||
assert "<a href=" not in html |