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.

joelhoro
  • 890
  • 1
  • 9
  • 20
  • 1
    Have you seen this? https://stackoverflow.com/questions/36897366/pandas-to-html-using-the-style-options-or-custom-css – dkreeft Jun 12 '20 at 06: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({...}) – Andreas Jun 12 '20 at 19:58
  • @Andreas - I added an example – joelhoro Jun 16 '20 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. – joelhoro Jun 16 '20 at 18:50

1 Answers1

1

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).

Alexander Pivovarov
  • 4,850
  • 1
  • 11
  • 34
  • 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 :) – joelhoro Jun 18 '20 at 04:47