Hello,
I want to show below dataframe styler using st.dataframe
but it is not showing the custom style as per given in make_bar_style
, Your inputs will be valuable:
import pandas as pd
import streamlit as st
# example multi-index dataframe
data = {'level_0': [1, 2, 3],
'level_1': ['A', 'B', 'C'],
'01/23/2023': ['20%', '30%', '40%'],
'01/24/2023': ['10%', '20%', '30%'],
'01/25/2023': ['15%', '25%', '35%'],
'01/26/2023': ['5%', '10%', '15%'],
'01/27/2023': ['1%', '2%', '3%']}
df = pd.DataFrame(data)
df = df.set_index(['level_0', 'level_1'])
def make_bar_style(x):
if '%' in str(x):
x = float(x.strip('%'))
return f"background: linear-gradient(90deg,#5fba7d {x}%, transparent {x}%); width: 10em"
return ''
st.dataframe(df.style.applymap(make_bar_style))
Thanks,
Nilesh
Hi @Nilesh_Dalvi ,
This should work with st.table
but not with st.dataframe
. st.dataframe
supports pandas styler but only background color, font color & display value. The reason is because st.dataframe uses HTML canvas and thus won’t likely be able to support this (won’t have access to the html dom with HTML canvas).
Hi @willhuang - Thanks for this, st.table
is working.
Hello @willhuang , does st.dataframe support background color, font color & display value for all streamlit versions? I’m in 1.22 because it’s the one available in Snowflake and it seems background does not work, and it would be quite nice. Here an example:
import streamlit as st
import pandas as pd
data = {
'A': [1, 2, 3, 4, 5],
'B': [5, 4, 3, 2, 1],
'C': [5, 4, 3, 2, 1],
}
df = pd.DataFrame(data)
def color_red_column(col):
return ['color: red' for _ in col]
def color_backgroubd_red_column(col):
return ['background: red' for _ in col]
styled_df = (df.style.apply(color_red_column, subset=['A'])
.apply(color_backgroubd_red_column, subset=['B']))
st.table(styled_df)
st.dataframe(styled_df)
And this is the result:
The background is ignored in st.dataframe (in st.table works fine).
Hi @Ricardo_Picatoste ,
thanks for asking your question. Setting background colors in st.dataframe should work. I just changed background: red' to
background-color: red` and that seemed to fix it.
import streamlit as st
import pandas as pd
data = {
'A': [1, 2, 3, 4, 5],
'B': [5, 4, 3, 2, 1],
'C': [5, 4, 3, 2, 1],
}
df = pd.DataFrame(data)
def color_red_column(col):
return ['color: red' for _ in col]
def color_backgroubd_red_column(col):
return ['background-color: red' for _ in col]
styled_df = (df.style.apply(color_red_column, subset=['A'])
.apply(color_backgroubd_red_column, subset=['B']))
st.table(styled_df)
st.dataframe(styled_df)
Thanks a lot @willhuang ! it does work indeed
Please let me take advantage to ask: do you know if this can be applied to the header? I do it with
import streamlit as st
import pandas as pd
data = {
'A': [1, 2, 3, 4, 5],
'B': [5, 4, 3, 2, 1],
'C': [5, 4, 3, 2, 1],
}
df = pd.DataFrame(data)
def color_red_column(col):
return ['color: red; font-weight: bold' for _ in col]
def color_backgroubd_red_column(col):
return ['background-color: red' for _ in col]
header_styles = {
'A': [{'selector': 'th', 'props': [('background-color', 'red')] }],
'B': [{'selector': 'th', 'props': [('background-color', 'blue')] }],
}
styled_df = (df.style.apply(color_red_column, subset=['A'])
.apply(color_backgroubd_red_column, subset=['B'])
.set_table_styles(header_styles)
)
st.table(styled_df)
st.dataframe(styled_df)
This locallly applies the style correctly with st.table, but not with st.dataframe. In snowflake it doesn’t work for st.table as expected.
The local screenshot:
And in snowflake:
If I manage to style the headers in st.dataframe, it would be a huge step.
1 Like
Hi @Ricardo_Picatoste , I don’t think it’s quite possible right now to style headers:
opened 04:28PM - 06 Jul 23 UTC
type:enhancement
feature:st.dataframe
feature:st.table
Hello everyone,
First off, I just wanted to say how wonderful is Streamlit as a… tool. It makes my life a lot easier.
### Problem
However, I encountered a slight drawback using `st.dataframe`. I'm making a dashboard and I need the tables to look as pretty as possible, and the styles of the header that I apply are not showing in app.
### Solution
**MVP:** Since the styles of the rows are working seamlessly, I figure using the same logic might work ?
### Additional context
Here is my code :
``` python
import pandas as pd
import numpy as np
def highlight_cells(data, color_config):
"""
Modify the style of a pandas dataframe.
Description:
Modify the style of a pandas dataframe, with a certain color config.
Gives a dark color to even rows and light color to uneven rows.
Args:
- data (pandas.DataFrame) : data to display in the table
- color_config (dict) : dict with color config
- 'columns' (list) : list of str, columns to highlight
- 'dark_color' (str) : even row color
- 'light_color' (str) : uneven row color
- 'header_color' (str) : header color
- 'header_bg_color' (str) : header background color
Returns:
- data (pandas.DataFrame) : data with modified style
"""
# Create an empty styler dataframe
styler = pd.DataFrame('', index=data.index, columns=data.columns)
header_styles = []
# For each color config
for config in color_config:
# For each column in the config
for col in config['columns']:
# If the column is in the dataframe
if col in data.columns:
# Apply the style to the column
styler[col] = np.where(styler.index % 2 == 0, f'background-color: {config["dark_color"]}; color: white', f'background-color: {config["light_color"]}; color: white')
header_styles.append({
'selector': f'th:nth-child({data.columns.get_loc(col) + 2})',
'props': [
('background-color', config['header_bg_color']),
('color', config['header_color'])
]
})
# Apply the style to the dataframe
df_styler = data.style.apply(lambda _: styler, axis=None)
df_styler.set_table_styles(header_styles)
return df_styler
```
When I use this in a Jupiter Notebook like this :
```python
df = pd.DataFrame(np.random.randn(10, 5), columns=list('ABCDE'))
color_config = [
{
'columns': ['A', 'B'],
'dark_color': '#808080',
'light_color': '#C0C0C0',
'header_color': '#808080',
'header_bg_color': '#C0C0C0'
},
{
'columns': ['C', 'D'],
'dark_color': '#800080',
'light_color': '#EE82EE',
'header_color': '#800080',
'header_bg_color': '#EE82EE'
}
]
highlight_cells(df, color_config)
```
I get this :

And when I try to use the same dataframe with streamlit :
``` python
import streamlit as st
def table(
data,
color_config=None,
index=False,
):
"""
Table component.
Description:
Table component that shows a pandas dataframe.
Args:
- data (pandas.DataFrame) : data to display in the table
- color_config (list of dicts), optionnal : list of dicts with color config, default None
- index (bool), optionnal : display index column, default False
"""
if color_config is not None:
data = highlight_cells(data, color_config)
st.dataframe(data, use_container_width=True, hide_index=not index)
return
table(df, color_config=color_config)
```
I get this :

Rows are good, but headers keep their standard style, so I was wondering if it would be possible to add this feature.
Thank you for your time,
Julien
---
Community voting on feature requests enables the Streamlit team to understand which features are most important to our users.
**If you'd like the Streamlit team to prioritize this feature request, please use the 👍 (thumbs up emoji) reaction in response to the initial post.**
You would likely need some custom css / hacky way of doing it if I had to guess.
Thank you for the heads up. I hope that now that streamlit is part of, and will run often in Snowflake, a solution that works in there will be prioritized.
I am pushing to have streamlit dashboards at the company, but not having the possibility of having properly formatted tables is a show-stopper.
Hi @Ricardo_Picatoste , I hear you and totally understand that not having the possibility of having properly formatted tables is a show-stopper on your side. I can let our product team know and see if we can get it prioritized.
If you could, can you upvote and comment on this issue:
opened 04:28PM - 06 Jul 23 UTC
type:enhancement
feature:st.dataframe
feature:st.table
Hello everyone,
First off, I just wanted to say how wonderful is Streamlit as a… tool. It makes my life a lot easier.
### Problem
However, I encountered a slight drawback using `st.dataframe`. I'm making a dashboard and I need the tables to look as pretty as possible, and the styles of the header that I apply are not showing in app.
### Solution
**MVP:** Since the styles of the rows are working seamlessly, I figure using the same logic might work ?
### Additional context
Here is my code :
``` python
import pandas as pd
import numpy as np
def highlight_cells(data, color_config):
"""
Modify the style of a pandas dataframe.
Description:
Modify the style of a pandas dataframe, with a certain color config.
Gives a dark color to even rows and light color to uneven rows.
Args:
- data (pandas.DataFrame) : data to display in the table
- color_config (dict) : dict with color config
- 'columns' (list) : list of str, columns to highlight
- 'dark_color' (str) : even row color
- 'light_color' (str) : uneven row color
- 'header_color' (str) : header color
- 'header_bg_color' (str) : header background color
Returns:
- data (pandas.DataFrame) : data with modified style
"""
# Create an empty styler dataframe
styler = pd.DataFrame('', index=data.index, columns=data.columns)
header_styles = []
# For each color config
for config in color_config:
# For each column in the config
for col in config['columns']:
# If the column is in the dataframe
if col in data.columns:
# Apply the style to the column
styler[col] = np.where(styler.index % 2 == 0, f'background-color: {config["dark_color"]}; color: white', f'background-color: {config["light_color"]}; color: white')
header_styles.append({
'selector': f'th:nth-child({data.columns.get_loc(col) + 2})',
'props': [
('background-color', config['header_bg_color']),
('color', config['header_color'])
]
})
# Apply the style to the dataframe
df_styler = data.style.apply(lambda _: styler, axis=None)
df_styler.set_table_styles(header_styles)
return df_styler
```
When I use this in a Jupiter Notebook like this :
```python
df = pd.DataFrame(np.random.randn(10, 5), columns=list('ABCDE'))
color_config = [
{
'columns': ['A', 'B'],
'dark_color': '#808080',
'light_color': '#C0C0C0',
'header_color': '#808080',
'header_bg_color': '#C0C0C0'
},
{
'columns': ['C', 'D'],
'dark_color': '#800080',
'light_color': '#EE82EE',
'header_color': '#800080',
'header_bg_color': '#EE82EE'
}
]
highlight_cells(df, color_config)
```
I get this :

And when I try to use the same dataframe with streamlit :
``` python
import streamlit as st
def table(
data,
color_config=None,
index=False,
):
"""
Table component.
Description:
Table component that shows a pandas dataframe.
Args:
- data (pandas.DataFrame) : data to display in the table
- color_config (list of dicts), optionnal : list of dicts with color config, default None
- index (bool), optionnal : display index column, default False
"""
if color_config is not None:
data = highlight_cells(data, color_config)
st.dataframe(data, use_container_width=True, hide_index=not index)
return
table(df, color_config=color_config)
```
I get this :

Rows are good, but headers keep their standard style, so I was wondering if it would be possible to add this feature.
Thank you for your time,
Julien
---
Community voting on feature requests enables the Streamlit team to understand which features are most important to our users.
**If you'd like the Streamlit team to prioritize this feature request, please use the 👍 (thumbs up emoji) reaction in response to the initial post.**
It helps our team understand where to put resources into and help prioritize.
Thanks @willhuang , and done, voted!