3

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.

1 Answer 1

2

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

4 Comments

Thanks for your answer! Actually, I'm looking for a solution different than returning it (if possible). I've edited my question with further details.
@David Have you tried displaying the styler from inside the function? Try doing that instead of returning the styler. I see you have copied code from the link you posted. That code won't work as you expect because it was meant to run as a script, not in the scope of a function.
oh, my bad! I definitely had to think more about what I was doing. I assumed that the style was somehow modified inplace in the df, but clearly pandas df does not embed a style (hence, `display.display(corr) does not displayed what I wanted). Displaying the styler indeed works! Thanks!
@David Great! I have amended my response.

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.