1

If I want to add html inside a normal dataframe, I can do

df.to_html(escape=False)

To ensure special characters are not escaped.

On the other hand if I want to use styles, I do

df.style.background_gradient(cmap='Blues').render()

How can I have both?

The render method seem to accept escape=False, but it doesn't do anything.

Additionally, my requirements are such that I would like to:

  1. have the gradient be applied on the original df
  2. be able to change some individual cells afterwards (specifically, I would like to make some cells clickable by surrounding them with <a onclick="...">...</a>

Anyone knows how to do this?

EDIT

Here is an example

import pandas as pd
df = pd.DataFrame([{'i': i*i } for i in range(10)])
df['clickable'] = df['i'].apply(lambda i: f"""<a onClick="alert('you pressed ' + {i})")>Click for {i}</a>""")
df.style.background_gradient(cmap='PuBu')

In the example above, I managed to get the 'clickable' column to be clickable. But I would like the 'i' column to be clickable too, while retaining its style.

4
  • 1
    Have you seen this? stackoverflow.com/questions/36897366/… Commented Jun 12, 2020 at 6:30
  • Could you post a sample input and expected output? You can easily create such an example like this: print(pd.read_clipboard().to_dict()) then put that dict into -> df = pd.DataFrame.from_dict({...}) Commented Jun 12, 2020 at 19:58
  • @Andreas - I added an example Commented Jun 16, 2020 at 18:48
  • @dkreeft - that post just explains what the render method is. My question is about how to use render but have the 'escape=False' set as well. Commented Jun 16, 2020 at 18:50

1 Answer 1

1
+100

I might be wrong, but it seems what you are looking for is something like this:

import pandas as pd
df = pd.DataFrame([{'i': i*i } for i in range(10)])
df.style.background_gradient(cmap='PuBu').format("""<a onClick="alert('{0}')">Click for {0}</a>""", subset=['i'])

This way apply allows you to apply gradients based on values and format allows you to tell styler how you want to render values (everywhere or in specific columns using subset).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - exactly what I was looking for. Turns out the argument for format can also be a lambda, which is what I need in my case. But you deserve the bounty :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.