[Python] How to calculate the percentage of list of values in each row in python pandas

Discussão em 'Python' iniciado por Stack, Junho 7, 2025.

  1. Stack

    Stack Membro Participativo

    I want to calculate the percentage of list of values each row . My data like

    pla_id vis_dm
    83393
    83394
    83395
    83393
    83395
    83423 [5, 6, 9, 12, 25, 28, 29, 30, 35, 40, 42, 64, ...
    83423 [5, 8, 9, 12, 25, 28, 39, 30, 35, 40, 42, 64, ...
    83426 [5, 7, 9, 12, 22, 28, 49, 30, 35, 40, 42, 64, ...
    83423 [5, 2, 9, 12, 28, 28, 29, 30, 35, 40, 42, 64, ...


    I need to calculate the percentage of each row values I need output like this :

    pla_id visitor_dma percentage of vis_dm
    83394
    83396
    83398
    83393
    83394
    83395
    83393
    83395
    83423 [4, 6, 9, 12, 25, 28, 29, 30, 35, 40, 42, 64, ... 60%
    83423 [7, 8, 9, 12, 15, 28, 29, 30, 35, 40, 42, 64, ... 40 %
    83426 [4, 6, 9, 12, 25, 18, 39, 40, 35, 40, 42, 64, ... 70%
    83423 [5, 2, 9, 12, 45, 98, 29, 30, 35, 40, 42, 64, ... 80%


    I tried this to code , I think still improve this code, can please anyone help me on this.

    plac['vist_dm'] = plac['vist_dm'].apply(
    lambda x: [' '] if isinstance(x, str) and x.strip() == '' else (
    ast.literal_eval(x) if isinstance(x, str) else x
    )
    )
    df_exploded1 = plac.explode('vist_dm')
    df_exploded2 = df_exploded1.rename(columns={'vist': 'dm'})

    dma_counts = df_exploded2['dm'].value_counts(normalize=True).round(4)
    df_exploded2['dm_percentage'] = df_exploded2['dm'].map(dm_counts)

    Continue reading...

Compartilhe esta Página