[Python] Setting row name during dataframe grouping

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

  1. Stack

    Stack Membro Participativo

    I have a dataframe like:

    name count
    -------------------
    apple pie 1
    applepie 3
    blueberries 2
    green tea 1


    I have some code to group rows where the name is the same value, but separated by spaces like:

    df["sans_spaces"] = df["name"].str.replace(" ", "")
    grouped_df = df.groupby("sans_spaces", as_index=False).aggregate({"count": "sum"})
    grouped_df


    This results in the following dataframe:

    name count
    -------------------
    applepie 4
    blueberries 2
    greentea 1


    I want the names in the end to be the space-separated value, so that grouped_df looks like:

    name count
    -------------------
    apple pie 4
    blueberries 2
    green tea 1


    Is there some way to do this?

    Continue reading...

Compartilhe esta Página