Home > database >  Combining one DF value based on other value in same DF
Combining one DF value based on other value in same DF

Time:06-15

I have a df as below

item_no | item_code | item_cost
1001       11111       150
1004       44444       100
1002       22222       120
1001       11112       150
1006       66666       180
1002       22221       160

How can i filter the df based on item_no and concat the item_code and add the item_cost and display them in a single row as below:

item_no |  item_code   | item_cost
1001      11111,11112       300
1004       44444            100
1002      22222,22221       280
1006       66666            180

Thanks,

CodePudding user response:

Use:

In [1354]: res = df.astype(str).groupby('item_no', as_index=False).agg({'item_code': ','.join, 'item_cost': lambda x: sum(map(int, x))})

In [1355]: res
Out[1355]: 
  item_no    item_code  item_cost
0    1001  11111,11112        300
1    1002  22222,22221        280
2    1004        44444        100
3    1006        66666        180
  • Related