[Python] Inconsistent results with pandas styler applymap

Discussão em 'Python' iniciado por Stack, Março 3, 2025.

  1. Stack

    Stack Membro Participativo

    So I am trying to style a pandas dataframe on a streamlit app. I was able to get it to style appropriately with the following code:

    df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9], 'X': [10, 11, 12], 'Y': [13, 14, 15], 'Z': [16, 17, 18]})

    default_colors = {
    "A": "brown",
    "B": "blue",
    "C": "green",
    "X": "orange",
    "Y": "red",
    "Z": "purple"
    }


    def highlight_columns(val, color):
    return f'color: {color}; font-weight: bold;' if val else ''

    if 'A' in df.columns:
    styled_df.applymap(lambda val: highlight_columns(val, default_colors['A']), subset=['A'])

    if 'B' in df.columns:
    styled_df.applymap(lambda val: highlight_columns(val, default_colors['B']), subset=['B'])

    if 'C' in df.columns:
    styled_df.applymap(lambda val: highlight_columns(val, default_colors['C']), subset=['C'])

    if 'X' in df.columns:
    styled_df.applymap(lambda val: highlight_columns(val, default_colors['X']), subset=['X'])

    if 'Y' in df.columns:
    styled_df.applymap(lambda val: highlight_columns(val, default_colors['Y']), subset=['Y'])

    if 'Z' in df.columns:
    styled_df.applymap(lambda val: highlight_columns(val, default_colors['Z']), subset=['Z'])


    But upon refactoring with:

    for column in 'ABCXYZ':
    if column in df.columns:
    styled_df.applymap(lambda val: highlight_columns(val, default_colors[column]), subset=[column])


    All columns iterated over are updated to the the final columns color. In this case column 'Z'. What is going on here? Why do the 6 if statements work fine but the loop doesn't?

    Continue reading...

Compartilhe esta Página