Search code examples
pythonpandasdataframesubtotal

how to adjust subtotal columns in pandas using grouby?


I'm working on exporting data frames to Excel using dataframe join.

However, after Join dataframe, when calculating subtotal using groupby, the figure below is executed.

There's a "Subtotal" word in the index column.

enter image description here

Is there any way to move it into the code column and sort the indexes?

enter image description here

here codes :

    def subtotal(df__, str):

        container = []


        for key, group in df__.groupby(['key']):
            group.loc['subtotal'] = group[['quantity', 'quantity2', 'quantity3']].sum()
            container.append(group)


        df_subtotal = pd.concat(container)
        df_subtotal.loc['GrandTotal'] = df__[['quantity', 'quantity2', 'quantity3']].sum()

        print(df_subtotal)
        return (df_subtotal.to_excel(writer, sheet_name=str))

Solution

  • Use np.where() to fill NaN in code column with value in df.index. Then assign a new index array to df.index.

    import numpy as np
    
    df['code']  = np.where(df['code'].isna(), df.index, df['code'])
    df.index = np.arange(1, len(df) + 1)
    
    print(df)
    
              code  key    product  quntity1  quntity2   quntity3
    1      cs01767    a    apple-a        10          0      10.0
    2     Subtotal  NaN        NaN        10          0      10.0
    3       cs0000    b  bannana-a        50         10      40.0
    4       cs0000    b  bannana-b         0          0       0.0
    5       cs0000    b  bannana-c         0          0       0.0
    6       cs0000    b  bannana-d        80         20      60.0
    7       cs0000    b  bannana-e         0          0       0.0
    8      cs01048    b  bannana-f         0          0       NaN
    9      cs01048    b  bannana-g         0          0       0.0
    10    Subtotal  NaN        NaN       130         30     100.0
    11     cs99999    c    melon-a        50         10      40.0
    12     cs99999    c    melon-b        20         20       0.0
    13     cs01188    c    melon-c        10          0      10.0
    14    Subtotal  NaN        NaN        80         30      50.0
    15  GrandTotal  NaN        NaN       220         60     160.0