3

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.

4
  • And you want the image to display in the cell? Commented Nov 21, 2016 at 16:16
  • Correct............ Commented Nov 21, 2016 at 16:19
  • Do we really need this many "...." :)? Commented Nov 21, 2016 at 16:31
  • 2
    No, but I don't want to fight with the minimum-character-width auto-enforcer. Commented Nov 21, 2016 at 16:48

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

is there any way to do this without having to call HTML(df.to_html(escape=False))? can the dataframe do it itself?
I couldn't find an option for it. I found one to not escape latex... that does us no good. You could overwrite the to_html method for that dataframe, but that is pretty hacky. I updated post with a function that will do it.
thanks! it's really hard to find all this information if you're not that familiar w/ libraries...
1

Here's an example:

from IPython.display import HTML
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
# this file is in the same folder as the notebook I'm using on my drive
df['image'] = 'so-logo.png'
df['new'] = df['image'].apply(lambda x: '<img src="{}"/>'.format(x) if x else '')
HTML(df.to_html(escape=False))

Simple result


Alternatively you can use df.styleinstead of IPython.display.HTML. This also allows you to add other formatting, for example to highlight the row on hover:

from IPython.display import HTML
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df['image'] = 'so-logo.png'
df['new'] = df['image'].apply(lambda x: '<img src="{}"/>'.format(x) if x else '')


def hover(hover_color="#ffff99"):
    return dict(selector="tr:hover",
                props=[("background-color", "%s" % hover_color)])

styles = [
    hover(),
    dict(selector="th", props=[("font-size", "150%"),
                               ("text-align", "center")]),
    dict(selector="caption", props=[("caption-side", "bottom")])
]
html = (df.style.set_table_styles(styles)
          .set_caption("Hover to highlight."))

html

I have my cursor on the second row here:

With hover

Comments

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.