[Python] How to bold part of a cell value in a pandas data frame while writing to excel using...

Discussão em 'Python' iniciado por Stack, Janeiro 30, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to bold semi colon and part of text that is before a semi colon in one of the columns in pandas dataframe.

    • Using ApplyMap , i am not getting the text before : highlighted

    import pandas as pd

    def highlight_before_colon(val):
    if ":" in val:
    before_colon, _ = val.split(":", 1)
    print(f'<b>{before_colon}</b>:{_}')
    return f'<b>{before_colon}</b>:{_}'
    else:
    return val

    df = pd.DataFrame({'Column1': ["Key1: Value1", "Key2: Value2"]})
    df.style.applymap(highlight_before_colon)


    Need the output:

    Column1
    Key1 : Value1
    Key2 : Value2
    • Using Apply , i can able to highlight whole cell not part of the data in the cell

    import pandas as pd

    def df_style(val):
    print(val)
    return ['font-weight: bold'] * len(val)

    summary = pd.DataFrame([[0, 45, 0, 0, 0], ['1620:304', '203', '392', '651', '2236']],
    index=["None", "Total"])

    summary.style.apply(df_style).to_excel("test.xlsx")

    display(summary.style.apply(df_style))

    Continue reading...

Compartilhe esta Página