I have been working on an application using Streamlit and I am having an issue with the formatting of my DataFrame. I have some columns that contain long strings of text, and they are not fully displayed within the cells of the DataFrame. Specifically, I have a column βCβ which contains Lorem Ipsum text that is very long.
I would like to modify the formatting of this DataFrame so that the entire contents of the βCβ column are displayed with automatic line breaks based on the width of the column. This would make it much easier for users to read the full text within the cell without having to scroll or manually adjust the cell size.
I have created a DataFrame using Pandas with three columns βAβ, βBβ, and βCβ, where βCβ contains the Lorem Ipsum text. Hereβs the code:
lorem_ipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ultrices ante nec justo varius, vitae gravida mi suscipit. Nullam vehicula facilisis semper. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed euismod nisl quis tellus lobortis, vitae blandit orci congue. Phasellus ullamcorper lacinia dolor, non suscipit dui dictum vel. Donec ac magna eget augue cursus finibus. Sed lacinia, justo eu tincidunt vestibulum, felis quam auctor nibh, nec ullamcorper augue elit vel elit."
df = pd.DataFrame({
"A": [1, 2, 3],
"B": ["a", "b", "c"],
"C": [lorem_ipsum, lorem_ipsum, lorem_ipsum]
})
st.dataframe(df,use_container_width=True)
But it is not yet possible to wrap the rendered cell or change the height of the row. However, you can use st.table (for smaller dataframes) which automatically applies cell wrapping:
You can manually replace the True/False values with HTML for disabled checkboxes to achieve the result. If you use the to_html method with keyword escape=False you get this:
import streamlit as st
import pandas as pd
lorem_ipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ultrices ante nec justo varius, vitae gravida mi suscipit. Nullam vehicula facilisis semper. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed euismod nisl quis tellus lobortis, vitae blandit orci congue. Phasellus ullamcorper lacinia dolor, non suscipit dui dictum vel. Donec ac magna eget augue cursus finibus. Sed lacinia, justo eu tincidunt vestibulum, felis quam auctor nibh, nec ullamcorper augue elit vel elit."
df = pd.DataFrame({
"A": [1, 2, 3],
"B": ["a", "b", "c"],
"C": [lorem_ipsum, lorem_ipsum, lorem_ipsum],
"D": [True,False,True]
})
true_html = '<input type="checkbox" checked disabled="true">'
false_html = '<input type="checkbox" disabled="true">'
df['D'] = df['D'].apply(lambda b: true_html if b else false_html)
st.markdown(df.to_html(escape=False), unsafe_allow_html=True)