[Python] Pandas percentage of total with groupby

Discussão em 'Python' iniciado por Stack, Julho 19, 2025.

  1. Stack

    Stack Membro Participativo

    This is obviously simple, but as a numpy newbe I'm getting stuck.

    I have a CSV file that contains 3 columns, the State, the Office ID, and the Sales for that office.

    I want to calculate the percentage of sales per office in a given state (total of all percentages in each state is 100%).

    df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
    'office_id': list(range(1, 7)) * 2,
    'sales': [np.random.randint(100000, 999999)
    for _ in range(12)]})

    df.groupby(['state', 'office_id']).agg({'sales': 'sum'})


    This returns:

    sales
    state office_id
    AZ 2 839507
    4 373917
    6 347225
    CA 1 798585
    3 890850
    5 454423
    CO 1 819975
    3 202969
    5 614011
    WA 2 163942
    4 369858
    6 959285


    I can't seem to figure out how to "reach up" to the state level of the groupby to total up the sales for the entire state to calculate the fraction.

    Continue reading...

Compartilhe esta Página