forked from streamlit/streamlit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataframe_styling.py
82 lines (69 loc) · 2.36 KB
/
dataframe_styling.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# -*- coding: utf-8 -*-
# Copyright 2018-2019 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Adapted from https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html
"""
import streamlit as st
import numpy as np
import pandas as pd
def color_negative_red(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
color = "red" if val < 0 else "black"
return "color: %s" % color
def highlight_max(data, color="yellow"):
"""highlight the maximum in a Series or DataFrame"""
attr = "background-color: {}".format(color)
if data.ndim == 1: # Series from .apply(axis=0) or axis=1
is_max = data == data.max()
return [attr if v else "" for v in is_max]
else: # from .apply(axis=None)
is_max = data == data.max().max()
return pd.DataFrame(
np.where(is_max, attr, ""), index=data.index, columns=data.columns
)
st.header("Dataframe styling")
# Create a dataframe to be styled in various ways
np.random.seed(24)
df = pd.DataFrame({"A": np.linspace(1, 5, 5)})
df = pd.concat([df, pd.DataFrame(np.random.randn(5, 4), columns=list("BCDE"))], axis=1)
df.iloc[0, 2] = np.nan
st.subheader("Unstyled")
st.dataframe(df)
st.subheader("Custom formatting")
st.dataframe(df.style.format("{:.2%}"))
st.subheader("Colors")
st.dataframe(
df.style.applymap(color_negative_red).apply(
highlight_max, color="darkorange", axis=0
)
)
st.subheader("Add rows")
x = st.dataframe(
df.style.set_properties(**{"background-color": "black", "color": "lawngreen"})
)
x.add_rows(
pd.DataFrame(np.random.randn(3, 5)).style.set_properties(
**{"background-color": "lawngreen", "color": "black"}
)
)
x.add_rows(
pd.DataFrame(np.random.randn(2, 5)).style.format(
lambda value: "" if value > 0 else "*"
)
)