2

I have a pandas dataframe that looks like this:

import pandas as pd
foo = pd.DataFrame({'temp': ['message1', 'message2', 'message3'], 'var2': [1,2,3], 'col3':[4,5,6]})

I also have the following dictionary

foo_dict = {'message1' : 'i am message 1', 'message2': 'i am foo',  'message3': 'i am lala', 'var2' : ' another random message', 'col3': 'more random messages'}

I would like to style this pandas dataframe, so that whenever I hover over an element of the dataframe, if this element (can be either a cell, or a column) exists in the foo_dict.keys(), i would like the respective foo_dict.value() to be annotated

Is it possible in pandas ?

quant
  • 4,062
  • 5
  • 29
  • 70

1 Answers1

5

As part of the the Styler Enhancements in pandas 1.3.0 there is now a set_tooltips function which can be used to set tool tips for the cells in the DataFrame.

Note, this is currently limited to "string based tooltips [that] are only applicable to HTML elements, and cannot be used for column or index headers."

import pandas as pd

foo = pd.DataFrame({
    'temp': ['message1', 'message2', 'message3'],
    'var2': [1, 2, 3],
    'col3': [4, 5, 6]
})

# Setup a DataFrame with corresponding hover values
tooltips_df = pd.DataFrame({
    'temp': ['i am message 1', 'i am foo', 'i am lala'],
    'var2': ' another random message',
    'col3': 'more random messages'
})

# Assign tooltips
foo.style.set_tooltips(tooltips_df)

styled table with hover tooltips

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • and to export to html you can change the last line to `foo.style.set_tooltips(tooltips_df).to_html('out.html')` see https://stackoverflow.com/a/36428285/5233269 – Richard DiSalvo Feb 25 '23 at 21:20