Search code examples
pythonpandasdataframeaggregate

To put the same rows together in a data frame


There is one data frame with three columns: model, lot, and qty

import pandas as pd

df = pd.DataFrame({'model':['A','A','A','B', 'B','B','C','C','C','C'],
               'lot':['x','x','y','y', 'y','y','y','y','z','z'],
                   'qty':[1,2,1,3,1,4,3,2,2,2]})

enter image description here

I want to put the same row together like below

Is it possible?

enter image description here


Solution

  • You can use:

    >>> df.groupby(['model', 'lot'], as_index=False)['qty'].sum()
      model lot  qty
    0     A   x    3
    1     A   y    1
    2     B   y    8
    3     C   y    5
    4     C   z    4