How to hide a column of a Styler DataFrame in Streamlit

Question:

I would like to delete a column or hide it after using it into a df.style.apply to display it into a Streamlit app.
Unfortunaly, each solution I tried doesn’t work as I want.

My code use the ‘anomaly’ column to highlight the row and after that, "try" to delete it or hide it to avoid the noise.

So, below my current code :

def anomaly_highlight(row):
    """Highlight a row in a dataframe according to a condition"""
    color = "#80003A" if row['anomaly'] == True else ''
    return [f'background-color:{color};'] * len(row)

df = pd.read_csv(upload)

model = IsolationForest(n_estimators=estimator, contamination=contamination,
                            max_samples='auto')

model.fit(df[keep_col])
df['anomaly'] = model.predict(df[keep_col]) == -1

df = df.style.apply(anomaly_highlight, axis=1)
# df_display = df.data.drop('anomaly', axis=1)
df = df.hide_columns('anomaly')

Delete a column or hide it after using it into a df.style.apply to display it into a Streamlit app

Asked By: CharleyD_L

||

Answers:

Try this:

df = df.style.hide_columns(['anomaly'])
df = df.apply(anomaly_highlight, axis=1)

Instead of:

df = df.style.apply(anomaly_highlight, axis=1)
# df_display = df.data.drop('anomaly', axis=1)
df = df.hide_columns('anomaly')
Answered By: Elodin

You need to render the styled df with to_html before displaying it in your app :

df_styled = df.style.apply(anomaly_highlight, axis=1)

df_styled_html = df_styled.hide("anomaly", axis=1).hide(axis=0).to_html()
#remove .hide(axis=0) if you need to preserve the index

st.write(df_styled_html, unsafe_allow_html=True)

Output (streamlit) :

enter image description here

Answered By: Timeless
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.