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

Question:

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
Asked By: Jason

||

Answers:

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

Answered By: Attack68
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.