0

I am trying to make a dataframe with clickable value using applymap() function. I already have it working using .format which is not what I'd prefer to be using.

data = [dict(name='Google', url='http://www.google.com'),
        dict(name='Stackoverflow', url='http://stackoverflow.com')]
df = pd.DataFrame(data)

df['nameurl'] = df['name'] + '#' + df['url']
def make_clickable_both(val): 
    name, url = val.split('#')
    return f'<a target="_blank" href="{url}">{name}</a>'

df.style.format({'nameurl': make_clickable_both})

enter image description here

However, using applymap() it does not seem to return html code and clickable link as I expected:

df.style.applymap(make_clickable_both, subset=['nameurl'])

enter image description here

ADDED

The reason I'm trying not to use .format is because I'm trying to implement it in streamlit.

Suggestion by @Henry Ecker seems (#3 in the code)to work in jupyter notebook, but does not generate clickable cell values in streamlit as shown below.

# 1
st.dataframe(df.style.applymap(make_clickable_both, subset=['nameurl']))
# 2 
st.dataframe(df.style.format({'nameurl': make_clickable_both}))
# 3
df['nameurl'] = df['nameurl'].apply(make_clickable_both)
st.dataframe(df.style)

enter image description here

user9532692
  • 584
  • 7
  • 28
  • This is not how `Styler.applymap` works. `applymap` returns styles (CSS) only. The current implementation is trying to apply an HTML anchor as CSS styles to the column (which is why it appears unformatted). `Styler.format` _is_ the appropriate Styler operation to change the content for repr purposes. You _could_ use normal DataFrame operations to modify the content first _e.g._ `df['nameurl'] = df['nameurl'].apply(make_clickable_both)` then just display with `df.style`. – Henry Ecker Oct 28 '22 at 23:03
  • What are you trying to achieve with `applymap` that you're not getting with `format`? Or more generally why is `Styler.format` not a reasonable solution for your use case? – Henry Ecker Oct 28 '22 at 23:04
  • @HenryEcker Thanks for your suggestion. As I edited in the post, I was trying to test it first in jupyter notebook and apply it in my streamlit app, but streamlit's `st.dataframe()` does not seem like it. – user9532692 Oct 29 '22 at 17:49
  • 1
    Unfortunately, I don't think you're going to get what you want here through streamlit. Their support for styled st.dataframe is limited. You can write the html `st.write(df.style.format({'nameurl': make_clickable_both}).to_html(escape=False), unsafe_allow_html=True)` [as demonstrated in this answer](/a/71737108/15497888). However, you will have a simple HTML table at the end; you will not have a styled st.dataframe that has the normal features provided by streamlit (_e.g._ sorting columns). – Henry Ecker Oct 29 '22 at 18:06

0 Answers0