How to use python dataframe styling in streamlit
Asked Answered
E

3

9

I have styled my dataframe using the below code:

th_props = [
  ('font-size', '14px'),
  ('text-align', 'center'),
  ('font-weight', 'bold'),
  ('color', '#6d6d6d'),
  ('background-color', '#f7ffff')
  ]

                                    
td_props = [
  ('font-size', '12px')
  ]
                                 

styles = [
  dict(selector="th", props=th_props),
  dict(selector="td", props=td_props)
  ]

df2=outputdframe.style.set_properties(**{'text-align': 'left'}).set_table_styles(styles)

But it doesn't work on streamlit. So, any idea how to style the dataframe on streamlit?

Image of the dataframe

Can anyone help me?

Evalynevan answered 14/7, 2021 at 13:54 Comment(0)
P
2

You should use st.table instead of st.dataframe. Here is some reproducible code:

# import packages
import streamlit as st
import pandas as pd
import numpy as np

# Example dataframe
outputdframe = pd.DataFrame(np.array([["CS", "University", "KR", 7032], ["IE", "Bangalore", "Bengaluru", 7861], ["CS", "Bangalore", "Bengaluru", 11036]]), columns=['Branch', 'College', 'Location', 'Cutoff'])

# style
th_props = [
  ('font-size', '14px'),
  ('text-align', 'center'),
  ('font-weight', 'bold'),
  ('color', '#6d6d6d'),
  ('background-color', '#f7ffff')
  ]
                               
td_props = [
  ('font-size', '12px')
  ]
                                 
styles = [
  dict(selector="th", props=th_props),
  dict(selector="td", props=td_props)
  ]

# table
df2=outputdframe.style.set_properties(**{'text-align': 'left'}).set_table_styles(styles)
st.table(df2)

Output:

enter image description here

Let's change the font size of the values in table by the value of "td_props" to "20" in the code:

enter image description here

Or change the colors of the header to red #FF0000 in "th_props" of the code like this:

enter image description here

So as you can see it changes the color of the headers. There are a lot of options to modify the style of your dataframe using st.table.

Paugh answered 14/9, 2022 at 16:1 Comment(0)
A
0

You need to pass the styled dataframe to Streamlit.

st.dataframe(df2)
Ardennes answered 26/8, 2022 at 1:18 Comment(1)
I am not sure if this works, right?Paugh
J
0

Pass the style (that you called it "df2") with html:

st.write(df2.to_html(), unsafe_allow_html=True))
Juvenility answered 23/11, 2022 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.