Exemplo n.º 1
0
    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)
Exemplo n.º 2
0
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&&lt;&gt;&amp;&#34;>X</td>'
    assert ex in s.render()
Exemplo n.º 3
0
    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
Exemplo n.º 4
0
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()
Exemplo n.º 5
0
 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
Exemplo n.º 6
0
    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"
Exemplo n.º 7
0
 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())
Exemplo n.º 8
0
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&&lt;&gt;&amp;&#34;>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&&lt;&gt;&amp;&#34;>X"
    assert ctx["head"][0][2]["display_value"] == "&"
Exemplo n.º 9
0
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
Exemplo n.º 10
0
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
Exemplo n.º 11
0
    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)
Exemplo n.º 12
0
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
Exemplo n.º 13
0
 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()
Exemplo n.º 14
0
    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)
Exemplo n.º 15
0
    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
Exemplo n.º 16
0
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()
    )
Exemplo n.º 17
0
    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
Exemplo n.º 18
0
 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
Exemplo n.º 19
0
    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)
Exemplo n.º 20
0
    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
Exemplo n.º 21
0
 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()
Exemplo n.º 22
0
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&&lt;&gt;&amp;&#34;>X</td>'
    expected2 = '<td id="T__row0_col1" class="data row0 col1" >&</td>'
    assert ex in s.render()
    assert expected2 in s.render()
Exemplo n.º 23
0
    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')
Exemplo n.º 24
0
    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'
Exemplo n.º 25
0
    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'
Exemplo n.º 26
0
    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"
Exemplo n.º 27
0
    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')
Exemplo n.º 28
0
    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"
Exemplo n.º 29
0
    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
Exemplo n.º 30
0
 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