Jason S Jason S - 13 days ago 11
Python Question

HTML formatting in Pandas DataFrame

Is there any way to add a formatted column in a Pandas DataFrame when working with it in IPython notebooks? I would like to add a data URL

<img>
and have it display in the cell.

Answer

If your src urls are too long, pandas will truncate them when it displays it. You need to increase the max column width to accomodate that.

track the current max column width

current_max_colwidth = pd.get_option('display.max_colwidth')
print(current_max_colwidth)

50

Set the option to something big

pd.set_option('display.max_colwidth', 1000)

import HTML display function

from IPython.display import HTML

use the dataframe to_html with the parameter escape=False

HTML(
    pd.DataFrame([
            """<img src="http://stackoverflow.com/users/flair/2336654.png?theme=default">""",
            """<img src="http://stackoverflow.com/users/flair/2543372.png?theme=default">""",
            """<img src="http://stackoverflow.com/users/flair/44330.png?theme=default">"""
        ]).to_html(escape=False))

enter image description here

Set option back

pd.set_option('display.max_colwidth', current_max_colwidth)

Wrap it up in a tidy function

def my_to_html(df):
    current_max_colwidth = pd.get_option('display.max_colwidth')
    pd.set_option('display.max_colwidth', 1000)
    from IPython.display import HTML
    my_html = HTML(df.to_html(escape=False))
    pd.set_option('display.max_colwidth', current_max_colwidth)
    return my_html

df = pd.DataFrame([
        """<img src="http://stackoverflow.com/users/flair/2336654.png?theme=default">""",
        """<img src="http://stackoverflow.com/users/flair/2543372.png?theme=default">""",
        """<img src="http://stackoverflow.com/users/flair/44330.png?theme=default">"""
    ])

my_to_html(df)
Comments