def test_precision(self): with pd.option_context('display.precision', 10): s = Styler(self.df) self.assertEqual(s.precision, 10) s = Styler(self.df, precision=2) self.assertEqual(s.precision, 2) s2 = s.set_precision(4) assert s is s2 self.assertEqual(s.precision, 4)
def test_format_escape(): df = DataFrame([['<>&"']]) s = Styler(df, uuid_len=0).format("X&{0}>X", escape=False) expected = '<td id="T__row0_col0" class="data row0 col0" >X&<>&">X</td>' assert expected in s.render() # only the value should be escaped before passing to the formatter s = Styler(df, uuid_len=0).format("X&{0}>X", escape=True) ex = '<td id="T__row0_col0" class="data row0 col0" >X&<>&">X</td>' assert ex in s.render()
def test_precision(self): with pd.option_context('display.precision', 10): s = Styler(self.df) assert s.precision == 10 s = Styler(self.df, precision=2) assert s.precision == 2 s2 = s.set_precision(4) assert s is s2 assert s.precision == 4
def test_format_escape_html(escape, exp): chars = '<>&"%$#_{}~^\\~ ^ \\ ' df = DataFrame([[chars]]) s = Styler(df, uuid_len=0).format("&{0}&", escape=None) expected = f'<td id="T__row0_col0" class="data row0 col0" >&{chars}&</td>' assert expected in s.to_html() # only the value should be escaped before passing to the formatter s = Styler(df, uuid_len=0).format("&{0}&", escape=escape) expected = f'<td id="T__row0_col0" class="data row0 col0" >&{exp}&</td>' assert expected in s.to_html()
def test_set_data_classes(self, classes): # GH 36159 df = DataFrame(data=[[0, 1], [2, 3]], columns=["A", "B"], index=["a", "b"]) s = Styler(df, uuid_len=0, cell_ids=False).set_td_classes(classes).render() assert '<td class="data row0 col0" >0</td>' in s assert '<td class="data row0 col1 test-class" >1</td>' in s assert '<td class="data row1 col0" >2</td>' in s assert '<td class="data row1 col1" >3</td>' in s # GH 39317 s = Styler(df, uuid_len=0, cell_ids=True).set_td_classes(classes).render() assert '<td id="T__row0_col0" class="data row0 col0" >0</td>' in s assert '<td id="T__row0_col1" class="data row0 col1 test-class" >1</td>' in s assert '<td id="T__row1_col0" class="data row1 col0" >2</td>' in s assert '<td id="T__row1_col1" class="data row1 col1" >3</td>' in s
def test_init_with_na_rep(self): # GH 21527 28358 df = DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"]) ctx = Styler(df, na_rep="NA")._translate() assert ctx["body"][0][1]["display_value"] == "NA" assert ctx["body"][0][2]["display_value"] == "NA"
def test_multiple_render(self): # GH 39396 s = Styler(self.df, uuid_len=0).applymap(lambda x: "color: red;", subset=["A"]) s.render() # do 2 renders to ensure css styles not duplicated assert ('<style type="text/css">\n#T__row0_col0, #T__row1_col0 {\n' " color: red;\n}\n</style>" in s.render())
def test_format_escape_na_rep(): # tests the na_rep is not escaped df = DataFrame([['<>&"', None]]) s = Styler(df, uuid_len=0).format("X&{0}>X", escape="html", na_rep="&") ex = '<td id="T__row0_col0" class="data row0 col0" >X&<>&">X</td>' expected2 = '<td id="T__row0_col1" class="data row0 col1" >&</td>' assert ex in s.to_html() assert expected2 in s.to_html() # also test for format_index() df = DataFrame(columns=['<>&"', None]) styler = Styler(df, uuid_len=0) styler.format_index("X&{0}>X", escape="html", na_rep="&", axis=1) ctx = styler._translate(True, True) assert ctx["head"][0][1]["display_value"] == "X&<>&">X" assert ctx["head"][0][2]["display_value"] == "&"
def style_index(data): styler = Styler(data.iloc[-1:], precision=2) def z_score(x): m = x.mean() return m - x.std() * 3, m + x.std() * 3 keys = [ "1D Perf.", "3M Perf.", "52W Perf.", "Rel. Volume", "1M RVol", "3M RVol" ] for key in keys: l, h = z_score(data[key]) styler = styler.background_gradient(cmap=CMAP, vmin=l, vmax=h, subset=[key]) keys = ['ATH Rank'] styler = styler.background_gradient(cmap=CMAP, vmin=-10, vmax=110, subset=keys) return styler
def test_latex_hiding_index_columns_multiindex_alignment(): # gh 43644 midx = MultiIndex.from_product([["i0", "j0"], ["i1"], ["i2", "j2"]], names=["i-0", "i-1", "i-2"]) cidx = MultiIndex.from_product([["c0"], ["c1", "d1"], ["c2", "d2"]], names=["c-0", "c-1", "c-2"]) df = DataFrame(np.arange(16).reshape(4, 4), index=midx, columns=cidx) styler = Styler(df, uuid_len=0) styler.hide_index(level=1).hide_columns(level=0) styler.hide_index([("i0", "i1", "i2")]) styler.hide_columns([("c0", "c1", "c2")]) styler.applymap(lambda x: "color:{red};" if x == 5 else "") styler.applymap_index(lambda x: "color:{blue};" if "j" in x else "") result = styler.to_latex() expected = dedent("""\ \\begin{tabular}{llrrr} & c-1 & c1 & \\multicolumn{2}{r}{d1} \\\\ & c-2 & d2 & c2 & d2 \\\\ i-0 & i-2 & & & \\\\ i0 & \\color{blue} j2 & \\color{red} 5 & 6 & 7 \\\\ \\multirow[c]{2}{*}{\\color{blue} j0} & i2 & 9 & 10 & 11 \\\\ \\color{blue} & \\color{blue} j2 & 13 & 14 & 15 \\\\ \\end{tabular} """) assert result == expected
def test_tooltip_render(self, ttips): # GH 21266 df = DataFrame(data=[[0, 3], [1, 2]], columns=["A", "B"], index=["a", "b"]) s = Styler(df, uuid_len=0).set_tooltips(ttips).render() # test tooltip table level class assert "#T__ .pd-t {\n visibility: hidden;\n" in s # test 'Min' tooltip added assert ( "#T__ #T__row0_col0:hover .pd-t {\n visibility: visible;\n}\n" + '#T__ #T__row0_col0 .pd-t::after {\n content: "Min";\n}' in s) assert ( '<td id="T__row0_col0" class="data row0 col0" >0<span class="pd-t">' + "</span></td>" in s) # test 'Max' tooltip added assert ( "#T__ #T__row0_col1:hover .pd-t {\n visibility: visible;\n}\n" + '#T__ #T__row0_col1 .pd-t::after {\n content: "Max";\n}' in s) assert ( '<td id="T__row0_col1" class="data row0 col1" >3<span class="pd-t">' + "</span></td>" in s)
def style_spread(data): styler = Styler(data.iloc[-1:], precision=2) def z_score(x): m = x.mean() return m - x.std() * 3, m + x.std() * 3 keys = [ 'Mean', '6M Corr.', '3M Corr.', 'Carry', 'Implied Spread', 'RVol Spread' ] for key in keys: l, h = z_score(data[key]) styler = styler.background_gradient(cmap=CMAP, vmin=l, vmax=h, subset=[key]) keys = ['Rank', 'Pct. Rank'] styler = styler.background_gradient(cmap=CMAP, vmin=-10, vmax=110, subset=keys) styler = styler.background_gradient(cmap=CMAP, vmin=-3, vmax=3, subset=["Z-Score"]) return styler
def test_render_double(self): df = pd.DataFrame({"A": [0, 1]}) style = lambda x: pd.Series( ["color: red; border: 1px", "color: blue; border: 2px"], name=x.name) s = Styler(df, uuid='AB').apply(style) s.render()
def test_nonunique_raises(self): df = pd.DataFrame([[1, 2]], columns=['A', 'A']) with pytest.raises(ValueError): df.style with pytest.raises(ValueError): Styler(df)
def test_tooltip_css_class(self): # GH 21266 df = DataFrame(data=[[0, 1], [2, 3]]) s = (Styler(df, uuid_len=0).set_tooltips(DataFrame([[ "tooltip" ]])).set_tooltips_class(name="other-class", properties=[("color", "green")]).render()) assert "#T__ .other-class {\n color: green;\n" in s assert '#T__ #T__row0_col0 .other-class::after {\n content: "tooltip";\n' in s # GH 39563 s = (Styler(df, uuid_len=0).set_tooltips(DataFrame([[ "tooltip" ]])).set_tooltips_class(name="other-class", properties="color:green;color:red;").render()) assert "#T__ .other-class {\n color: green;\n color: red;\n}" in s
def test_rowspan_w3(): # GH 38533 df = DataFrame(data=[[1, 2]], index=[["l0", "l0"], ["l1a", "l1b"]]) styler = Styler(df, uuid="_", cell_ids=False) assert ( '<th id="T___level0_row0" class="row_heading ' 'level0 row0" rowspan="2">l0</th>' in styler.render() )
def test_precision(self): s = Styler(self.df, precision=2) assert s.precision == 2 with tm.assert_produces_warning(FutureWarning): s2 = s.set_precision(4) assert s is s2 assert s.precision == 4
def test_no_cell_ids(self): # GH 35588 # GH 35663 df = DataFrame(data=[[0]]) styler = Styler(df, uuid="_", cell_ids=False) styler.render() s = styler.render() # render twice to ensure ctx is not updated assert s.find('<td class="data row0 col0" >') != -1
def test_nonunique_raises(self): df = DataFrame([[1, 2]], columns=["A", "A"]) msg = "style is not supported for non-unique indices." with pytest.raises(ValueError, match=msg): df.style with pytest.raises(ValueError, match=msg): Styler(df)
def test_table_attributes(self): attributes = 'class="foo" data-bar' styler = Styler(self.df, table_attributes=attributes) result = styler.render() assert 'class="foo" data-bar' in result result = self.df.style.set_table_attributes(attributes).render() assert 'class="foo" data-bar' in result
def test_render_empty_dfs(self): empty_df = DataFrame() es = Styler(empty_df) es.render() # An index but no columns DataFrame(columns=['a']).style.render() # A column but no index DataFrame(index=['a']).style.render()
def test_format_escape_na_rep(): # tests the na_rep is not escaped df = DataFrame([['<>&"', None]]) s = Styler(df, uuid_len=0).format("X&{0}>X", escape=True, na_rep="&") ex = '<td id="T__row0_col0" class="data row0 col0" >X&<>&">X</td>' expected2 = '<td id="T__row0_col1" class="data row0 col1" >&</td>' assert ex in s.render() assert expected2 in s.render()
def test_uuid(self): styler = Styler(self.df, uuid='abc123') result = styler.render() self.assertTrue('abc123' in result) styler = self.df.style result = styler.set_uuid('aaa') self.assertTrue(result is styler) self.assertEqual(result.uuid, 'aaa')
def test_uuid(self): styler = Styler(self.df, uuid='abc123') result = styler.render() assert 'abc123' in result styler = self.df.style result = styler.set_uuid('aaa') assert result is styler assert result.uuid == 'aaa'
def test_caption(self): styler = Styler(self.df, caption='foo') result = styler.render() assert all(['caption' in result, 'foo' in result]) styler = self.df.style result = styler.set_caption('baz') assert styler is result assert styler.caption == 'baz'
def test_uuid(self): styler = Styler(self.df, uuid="abc123") result = styler.render() assert "abc123" in result styler = self.df.style result = styler.set_uuid("aaa") assert result is styler assert result.uuid == "aaa"
def test_caption(self): styler = Styler(self.df, caption='foo') result = styler.render() self.assertTrue(all(['caption' in result, 'foo' in result])) styler = self.df.style result = styler.set_caption('baz') self.assertTrue(styler is result) self.assertEqual(styler.caption, 'baz')
def test_caption(self): styler = Styler(self.df, caption="foo") result = styler.render() assert all(["caption" in result, "foo" in result]) styler = self.df.style result = styler.set_caption("baz") assert styler is result assert styler.caption == "baz"
def test_table_styles(self): style = [{'selector': 'th', 'props': [('foo', 'bar')]}] styler = Styler(self.df, table_styles=style) result = ' '.join(styler.render().split()) assert 'th { foo: bar; }' in result styler = self.df.style result = styler.set_table_styles(style) assert styler is result assert styler.table_styles == style
def test_uuid_len(self, len_): # GH 36345 df = DataFrame(data=[["A"]]) s = Styler(df, uuid_len=len_, cell_ids=False).render() strt = s.find('id="T_') end = s[strt + 6:].find('"') if len_ > 32: assert end == 32 + 1 else: assert end == len_ + 1