0

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 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

8 Comments

it is not data frame. It is a data frame styled object that has nan values that I need to remove while keeping the style in tact.
I get this error: 'Styler' object has no attribute 'loc'
That's because you need to get the dataframe object from the styler to work with it, I have updated the answer once again.
Also it's not a good practice to name styled objects with regular dataframe variable names, consider adding styled or styler in the variable name.
"styler_obj.data = " does not work. if I remove data, it works but removes the style while updating the sytled object data
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.