How to left align column headers and values in a dataframe?

I am very new to Streamlit. Pls help me.

pd.option_context(‘colheader_justify’, ‘left’)
pd.set_option(‘colheader_justify’, ‘left’)

The above commands do not work.

df2=outputdframe.style.set_properties(**{‘text-align’: ‘left’}).set_table_styles([dict(selector=‘th’, props=[(‘text-align’, ‘left’)])])

With the above line, only the data values align to left but not the column headers.

Hey @VISHNU_SASTRY_H_K_CS Welcome to the community !

Its hacky but I think this should work,
( It will force alignment of all of the dataframe content of all of your dataframes to left )

st.markdown(
    """<style>
        .dataframe {text-align: left !important}
    </style>
    """, unsafe_allow_html=True) 
3 Likes

This is not working…

Hi @Vishnu_Sastry_H_K , as I mentioned that the solution is hacky because it overrides alignment on streamlit’s css classes.

As of 0.87 version in streamlit the class for headers is .col_heading so this will work now,

st.markdown(
    """<style>
        .col_heading   {text-align: left !important}
    </style>
    """, unsafe_allow_html=True) 

Hope it helps !

I tried using it for the data frame contents but doesn’t seem to work. I could care less about the column headers, my users are just struggling to read longer text entries in the DF. Any other reason why:

st.markdown(
    """<style>
        .dataframe {text-align: left !important}
    </style>
    """, unsafe_allow_html=True)

wont work?

Hi @rzw3ch,

Left alignment of values can be done natively in Pandas with styler functions. Here’s a reproducible example:

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

@st.cache
def load_data():
    return pd.read_csv(
        "https://raw.githubusercontent.com/vaksakalli/datasets/master/diabetes.csv"
        )

def left_align(s, props='text-align: left;'):
    return props

df = load_data()

if st.checkbox('Left align values', value=False):
    st.dataframe(df.style.applymap(left_align))
else:
    df

pandas-align

Does this help?

Happy Streamlit’ing! :balloon:
Snehan

I see why you did this…but, I feel super dumb because I do not understand how to set the styler when I instantiate the df in this way:

st.dataframe(df[(df.priority.isin(prioritySelection)) & (df.lineNum.between(dtSelection[0], dtSelection[1])) & (df.app.str.contains(keyword)) & (df.message.str.contains(keyword))])

I am not sure how to call the method when there are a bunch of nested filters for the df at the same time.

The sample code provided by @snehankekre no longer works. That is, when you click the checkbox to left align, the alignment doesn’t change as it does in his video. Is this a bug? Or, if there is another way to do this now, then what is it?

To reproduce, I saved the script he provided as test.py, and changed the data source to the one below because the diabetes.csv file is no longer available. When I run it, you can see that in the screen shot I uploaded, the checkbox is checked but the text in the first column is not left-aligned. If you change the script to do ‘text-align:center’ then it’s more obvious that nothing is happening.

This is in Chrome and Edge.

https://media.githubusercontent.com/media/datablist/sample-csv-files/main/files/customers/customers-100.csv

While there is no direct method to center the contents of a table, you can achieve the desired alignment of text within the dataframe by converting it to an HTML-based table using the following code:

import pandas as pd
import streamlit as st

# Intialize a list of tuples containing the CSS styles for table headers
th_props = [('font-size', '14px'), ('text-align', 'left'),
            ('font-weight', 'bold'),('color', '#6d6d6d'),
            ('background-color', '#eeeeef'), ('border','1px solid #eeeeef'),
    ]

# Intialize a list of tuples containing the CSS styles for table data
td_props = [('font-size', '14px'), ('text-align', 'center')]

# Define hover props for table data and headers
cell_hover_props = [('background-color', '#eeeeef')]
headers_props = [('text-align','center'), ('font-size','1.1em')]

# Aggregate styles in a list
styles = [
    dict(selector="th", props=th_props),
    dict(selector="td", props=td_props),
    dict(selector="td:hover",props=cell_hover_props),
    dict(selector='th.col_heading',props=headers_props),
    dict(selector='th.col_heading.level0',props=headers_props),
    dict(selector='th.col_heading.level1',props=td_props)
]

# Create a sample DataFrame
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [11, 12, 13], 'D': [14, 15, 16]}
dataframe = pd.DataFrame(data)

# Use markdown to show the table as HTML as opposed to the streamlit version table
st.markdown(dataframe.T.style.set_table_styles(styles).to_html(), unsafe_allow_html=True)

I hope this helps.