Skip to content
Advertisement

Display pandas dataframe using custom style inside function in IPython

In a jupyter notebook, I have a function which prepares the input features and targets matrices for a tensorflow model.

Inside this function, I would like to display a correlation matrix with a background gradient to better see the strongly correlated features.

This answer shows how to do that exactly how I want to do it. The problem is that from the inside of a function I cannot get any output, i.e. this:

def display_corr_matrix_custom():
    rs = np.random.RandomState(0)
    df = pd.DataFrame(rs.rand(10, 10))
    corr = df.corr()
    corr.style.background_gradient(cmap='coolwarm')

display_corr_matrix_custom()

clearly does not show anything. Normally, I use IPython’s display.display() function. In this case, however, I cannot use it since I want to retain my custom background.

Is there another way to display this matrix (if possible, without matplotlib) without returning it?


EDIT: Inside my real function, I also display other stuff (as data description) and I would like to display the correlation matrix at a precise location. Furthermore, my function returns many dataframes, so returning the matrix as proposed by @brentertainer does not directly display the matrix.

Advertisement

Answer

You mostly have it. Two changes:

  • Get the Styler object based from corr.
  • Display the styler in the function using IPython’s display.display()
def display_corr_matrix_custom():
    rs = np.random.RandomState(0)
    df = pd.DataFrame(rs.rand(10, 10))
    corr = df.corr()  # corr is a DataFrame
    styler = corr.style.background_gradient(cmap='coolwarm')  # styler is a Styler
    display(styler)  # using Jupyter's display() function

display_corr_matrix_custom()
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement