[Python] Merge cells in a pandas dataframe [duplicate]

Discussão em 'Python' iniciado por Stack, Setembro 26, 2024.

  1. Stack

    Stack Membro Participativo

    I have the below dataframe in pandas:

    Company Name Product App Name August-2024 September-2024 YTD Credits
    Company A Prod 1 App 1 12 13 25
    Company A Prod 1 App 2 22 25 47
    Company B Prod 2 App 3 10 10 20
    Company C Prod 3 App 4 9 1 10
    Company C Prod 1 App 1 4 10 14
    Company C Prod 4 App 5 3 9 12

    I need to merge the rows in the above dataframe which have the same Company Name and I need to calculate the sum of YTD Credits for each Company and create a new column - Total Credits. The resultant table would look like below:


    desired result


    I can calculate the Total Credits using:

    df['Total Credits'] = df.groupby('Company Name')['YTD Credits'].transform('sum')


    I can merge the cell in the Company Name using:

    company_wise_df = pd.DataFrame(df).set_index(['Company Name', 'Product'])


    The final table looks as below:


    current table


    However, I am unable to merge the cells in the Total Credits column.

    Continue reading...

Compartilhe esta Página