Search code examples
pythonpandasdataframepandas-styles

How to assign new `styler` object to pandas DataFrame?


Why can't I assign a new style to pandas dataframe? The following assignment (last line) doesn't work but I would like to change a style of a given dataframe in some functions and such a functionality would be great:

import pandas as pd
import numpy as np

def color_negative(v, color):
    return f"color: {color};" if v < 0 else None
df = pd.DataFrame(np.random.randn(5, 2), columns=["A", "B"])
s = df.style
s = s.applymap(color_negative, color='green', subset=["B"])
s = s.applymap(color_negative, color='red', subset=["A"])
 
df.style = s

Solution

  • I think you are trying to emulate the styler.use and .export methods.

    import pandas as pd
    import numpy as np
    def color_negative(v, color):
        return f"color: {color};" if v < 0 else None
    df = pd.DataFrame(np.random.randn(5, 2), columns=["A", "B"])
    s = df.style
    s = s.applymap(color_negative, color='green', subset=["B"])
    s = s.applymap(color_negative, color='red', subset=["A"])
    s = s.export()
    
    df.style.use(s)
    

    enter image description here