Hyperlink in Streamlit dataframe
Asked Answered
A

2

7

I am attempting to display a clickable hyperlink inside a dataframe containing filtered results on Streamlit. This is my code so far:

import pandas as pd
import streamlit as st
import openpyxl
import numpy as np
from IPython.core.display import display, HTML

df = pd.read_excel(

  io='list.xlsx',
  engine= 'openpyxl',
 ).fillna('')

def make_clickable(link):
    # target _blank to open new window
    # extract clickable text to display for your link
    text = link.split('=')[0]
    return f'<a target="_blank" href="{link}">{text}</a>'

# TRAILER is the column with hyperlinks
df['TRAILER'] = df['TRAILER'].apply(make_clickable)

df['TRAILER'] = HTML(display(df.to_html(render_links=True, escape=False), raw=True))

If I use:

df['TRAILER'] = df['TRAILER'].apply(make_clickable)

I get

<a target="_blank" href="{link}">{text}</a>

displayed as a string but not a hyperlink.

When I add:

df['TRAILER'] = HTML(display(df.to_html(render_links=True, escape=False), raw=True))

I get:

<IPython.core.display.HTML object>

displayed as a string but not a hyperlink.

These are the versions I am using. Other components of the site work only with a lower version of Streamlit which is why I am using this version.

streamlit == 0.83 numpy == 1.18 pandas == 1.2 openpyxl ipython == 7.22 python == 3.9

site screenshot

I cannot use st.markdown or st.write directly as I am using st.dataframe to display the results.

Animism answered 28/3, 2022 at 1:54 Comment(1)
I think this can help Display URLs in dataframe column as a clickable hyperlink. Also please provide some sample data and your desired output. (See How to make good reproducible pandas examples).Episode
F
6

You can use st.write(df.to_html(escape=False, index=False), unsafe_allow_html=True):

import pandas as pd
import streamlit as st
import openpyxl
import numpy as np
from IPython.core.display import display, HTML

df = pd.read_excel(
  io='list.xlsx',
  engine= 'openpyxl',
 ).fillna('')

def make_clickable(link):
    # target _blank to open new window
    # extract clickable text to display for your link
    text = link.split('=')[0]
    return f'<a target="_blank" href="{link}">{text}</a>'

# TRAILER is the column with hyperlinks
df['TRAILER'] = df['TRAILER'].apply(make_clickable)

st.write(df.to_html(escape=False, index=False), unsafe_allow_html=True)

On a working example:

import pandas as pd
import streamlit as st

link1 = "https://mcmap.net/q/1461300/-hyperlink-in-streamlit-dataframe"
link2 = "https://mcmap.net/q/1480860/-how-to-plot-comparison-in-streamlit-dynamically-with-multiselect"
df = pd.DataFrame(
    {
        "url": [
            f'<a target="_blank" href="{link1}">Hyperlink in Streamlit dataframe</a>',
            f'<a target="_blank" href="{link2}">How to plot comparison in Streamlit dynamically with multiselect?</a>'
        ],
        "label": ["question", "question"]
    }
)

st.write(df.to_html(escape=False, index=False), unsafe_allow_html=True)

It gives:

Hyperlinks to SO questions (dataframe)

Filch answered 4/4, 2022 at 12:15 Comment(5)
I cant use st.write or st.markdown as it wont show the final spreadsheet with the filtered results. I have already tried this.Animism
Did you find a solution to your problem?Catchings
@PhilippGärtner This will likely be implemented in streamlit in 2023Crinoid
you will lose all other built-in features (etc. sort and search).Biramous
This is now a built-in feature. See my answer or the doc: docs.streamlit.io/library/api-reference/data/st.column_config/…Distemper
D
4

This feature is now available directly in streamlit via the LinkColumn (see doc for more details) configuration.

Here is an example of how to use it:

import pandas as pd
import streamlit as st

df = pd.DataFrame(
    [
        {"name": "Google", "url": "http://google.com"},
        {
            "name": "Streamlit Link Column",
            "url": "https://docs.streamlit.io/library/api-reference/data/st.column_config/st.column_config.linkcolumn",
        },
    ]
)

st.header("DataFrame")
st.dataframe(
    df,
    column_config={"url": st.column_config.LinkColumn("URL to website")},
)

Example Screenshot

Distemper answered 26/9, 2023 at 9:36 Comment(2)
Now display_text is also added to create readable link text instead of showing full url. On the example, you can use st.dataframe(df, column_config={"url", st.column_config.LinkColumn("URL to website", display_text="https://docs.streamlit.io/library/api-reference/data/(.*)")}). The link can show as st.column_config/st.column_config.linkcolumnLeilaleilah
To add up on @EricSun 's comment, it uses a regular expression and display the text with what is matched between the parentheses. For example, if you have https://my-database.com/query?id=123, then you could set display_text="https://my-database.com/query?id=(\d+)" to show 123 with a link to your database. ... maybe I should update my answer to add this :)Distemper

© 2022 - 2024 — McMap. All rights reserved.