Search code examples
pandascolorsgradientpandas-styles

Color gradient fill in pandas dataframe


I have this panda dataframe:

enter image description here

and I need to add a color gradient fill in the WoE column, so that it looks like this:

enter image description here

Does anyone know if and how to do that?


Solution

  • You can use DataFrame.style to plot a bar, aligned with 'zero', and you can specify the colors for positive and negative values. You will first need to make sure your Series has a numeric dtype, so that empty cell needs to be replaced with NaN

    Sample Data

    import pandas as pd
    df = pd.DataFrame({'col1': list('ABCDEFG'),
                       'col2': list('xywerwr'),
                       'WOE': [-.08, -.03, .01, .09, .15, .24, '']})
    

    Code

    df['WOE'] = pd.to_numeric(df['WOE'])
    df.style.bar(subset=['WOE'], align='zero', color=['#BA4B2F', '#7AAFe0'])
    

    enter image description here