Skip to content

🚩  Image in tables

Submitted by dataprofessor

Summary

Transform URLs into images in your dataframes

Functions

table_with_images

Generate the HTML of a table with images rendered in it.

Parameters:

Name Type Description Default
df DataFrame

Original dataframe

required
url_columns Iterable

Column in df which contains URLs

required

Returns:

Name Type Description
table_html str

HTML of the table with images

Source code in src/streamlit_extras/image_in_tables/__init__.py
@extra
@cache_data
def table_with_images(df: pd.DataFrame, url_columns: Iterable) -> str:
    """
    Generate the HTML of a table with images rendered in it.

    Args:
        df (pd.DataFrame): Original dataframe
        url_columns (Iterable): Column in df which contains URLs

    Returns:
        table_html (str): HTML of the table with images
    """

    df_ = df.copy()

    @cache_data
    def _path_to_image_html(path):
        return '<img src="' + path + '" width="60" >'

    for column in url_columns:
        df_[column] = df_[column].apply(_path_to_image_html)

    table_html = df_.to_html(escape=False)

    return table_html

Import:

from streamlit_extras.image_in_tables import table_with_images # (1)!
  1. You should add this to the top of your .py file 🛠

Examples

example

def example(df: pd.DataFrame):
    st.caption("Input dataframe (notice 'Flag' column is full of URLs)")
    st.write(df)
    df_html = table_with_images(df=df, url_columns=("Flag",))
    st.caption("Ouput")
    st.markdown(df_html, unsafe_allow_html=True)