pythonpython-3.xpandaspandas-styles

How to annotate labels when you hover over a pandas dataframe


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 ?


Solution

  • 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 <td> 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