简体   繁体   中英

Pandas style background gradient not showing in jupyter notebook

I am trying to print a pandas dataframe with a background gradient for better readability. I tried to apply what I found in the docs to a simple use case, but I can't get jupyter notebook to actually print the table with the colors - I keep getting the plain dataframe. Small example:

import seaborn as sns
import pandas as pd


cm = sns.light_palette('green', as_cmap=True)
df_res = pd.DataFrame(index =['foo','bar'],columns = ['Value 1','Value 2','Value 3'])
df_res.loc['foo'] = [-.5*100, .3,.2]
df_res.loc['bar'] = [.3*100, .6,.9]
df_res.style.background_gradient(cmap=cm)

which just prints

这个简单的数据框 .

I tried different printing techniques, ie

pretty = df_res.style.background_gradient(cmap=cm)
display(pretty)

or

print(pretty)

or a different colormap

df_res.style.background_gradient(cmap='viridis')

but none of them work. I also tried if the styler works at all, but at least the applymap function does what it's supposed to:

def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color
df_res.style.applymap(color_negative_red)

which prints

So not sure why the background_gradient doesn't seem to have any effect.

EDIT : Just found the reason. It's a simple fix but in case someone else struggles with the same problem I'm keeping this up. Apparently pandas initialized the dataframe with the elements being objects instead of floats. So simple changing initialization to

df_res = pd.DataFrame(index =['foo','bar'],columns = ['Value 1','Value 2','Value 3']).astype('float')

solved the issue.

Your dtypes of your dataframe are 'object' and not numeric.

First, change the dtype in your dataframe to numeric.

df_res.apply(pd.to_numeric).style.background_gradient(cmap=cm)

Output: 在此处输入图片说明


Note dtypes:

import seaborn as sns
import pandas as pd


cm = sns.light_palette('green', as_cmap=True)
df_res = pd.DataFrame(index =['foo','bar'],columns = ['Value 1','Value 2','Value 3'])
df_res.loc['foo'] = [-.5*100, .3,.2]
df_res.loc['bar'] = [.3*100, .6,.9]
df_res.info()

Output:

<class 'pandas.core.frame.DataFrame'>
Index: 2 entries, foo to bar
Data columns (total 3 columns):
Value 1    2 non-null object
Value 2    2 non-null object
Value 3    2 non-null object
dtypes: object(3)
memory usage: 144.0+ bytes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM