Dropping columns used as condition when highlighting the column in Pandas

164 views Asked by At

I have highlighted pandas dataframe using conditional statement (highlight one column as yellow if other column value is True). Before exporting to Excel I want to remove the conditional column I used. But I got error message.

Here is what I have done:

enter image description here

Here is my code:

def highlight_col(val):
    data = pd.DataFrame('', index=val.index, columns=val.columns)
    if val['Email Updated'].any():
        data.loc[val['Email Updated'], 'Email'] = f"background-color: yellow"
    return data

styled_df = df.style.apply(highlight_col, axis=None)
styled_df.to_excel('filename.xlsx', index = False)

After export I want to drop Email Updated column and keep email column.

So far I have tried

data.drop('Email Updated', axis = 1, inplace = True)

and

styled_df.drop('Email Updated', axis = 1, inplace = True)

But without success.

Thank you!

1

There are 1 answers

6
Timeless On BEST ANSWER

Here is one of the options :

import numpy as np

#is email updated ?
m = df["Email Updated"]

styled_df = (df.drop(columns="Email Updated").style.apply(
             lambda _: np.where(m, f"background-color: yellow", ""), subset="Email"))

#another variant
#styled_df = (df[["Email"]].style.apply( #feel free to add more columns
#             lambda _: np.where(m, f"background-color: yellow", ""), subset="Email"))

styled_df.to_excel("filename.xlsx", index=False)

Or, following your approach (for pandas >= 1.4.0), you can chain it with hide :

styled_df = (df.style.apply(highlight_col, axis=None)
                     .hide(subset=["Email Updated"], axis=1))

Output :

enter image description here