how do you remove text from Pandas styled object while keeping the style in place

105 views Asked by At

I have a styled object that some of the cells have nan values. I need to remove the nan values while I keep the style in place.

enter image description here

if I do this:

new_df.data.replace(np.nan, '', regex=True)

this removes the nan values as well as the style.

Is there a way to keep the style while removing nan values from the Pandas styled object.

2

There are 2 answers

8
Ahmad Hamdi On BEST ANSWER

Edit: I noticed your issue is with the styles.

You could use this oneliner:

styler_obj.data.where(~styler_obj.data.isna(), '', inplace=True)

If you don't care about the styles you can simply use DataFrame.replace like this:

df.replace('NaN', '', inplace=True)

Or get a little bit fancy using types from Numpy like this:

import numpy as np
df.replace(np.nan, '', inplace=True)
0
Timeless On

IIUC, you can use :

#df from here https://stackoverflow.com/questions/77061724

import numpy as np

TARGET = "Percent_Utilized"

def color(ser):
    conds = [ser.gt(80), ser.between(50, 80, inclusive="right"), ser.isnull()]
    vals = ["background-color: red", "background-color: yellow", ""]
    return np.select(conds, vals, default="background-color: green")

s = (
    df.style
        .apply(color, subset=TARGET)
        .format("{:.0f}%", na_rep="", subset=TARGET)
        .format(na_rep="", subset="Model") # optional
)

Output :

enter image description here