简体   繁体   中英

Pandas Group by sum of all the values of the group and another column as comma separated

I want to group by one column (tag) and sum up the corresponding quantites (qty). The related reference no. column should be separated by commas

import pandas as pd

tag = ['PO_001045M100960','PO_001045M100960','PO_001045MSP2526','PO_001045M870191', 'PO_001045M870191', 'PO_001045M870191']
reference= ['PA_000003', 'PA_000005', 'PA_000001', 'PA_000002', 'PA_000004', 'PA_000009']
qty=[4,2,2,1,1,1]

df = pd.DataFrame({'tag' : tag, 'reference':reference, 'qty':qty})

      tag           reference   qty
PO_001045M100960    PA_000003   4
PO_001045M100960    PA_000005   2
PO_001045MSP2526    PA_000001   2
PO_001045M870191    PA_000002   1
PO_001045M870191    PA_000004   1
PO_001045M870191    PA_000009   1

If I use df.groupby('tag')['qty'].sum().reset_index(), I am getting the following result.

         tag           qty
ASL_PO_000001045M100960 6
ASL_PO_000001045M870191 3
ASL_PO_000001045MSP2526 2

I need an additional column where the reference no. are added under the respective tags like,

         tag           qty     refrence
ASL_PO_000001045M100960 6      PA_000003, PA_000005
ASL_PO_000001045M870191 3      PA_000002, PA_000004, PA_000009
ASL_PO_000001045MSP2526 2      PA_000001

How can I achieve this?

Thanks.

Use pandas.DataFrame.groupby.agg :

df.groupby('tag').agg({'qty': 'sum', 'reference': ', '.join})

Output:

                                        reference  qty
tag                                                   
PO_001045M100960             PA_000003, PA_000005    6
PO_001045M870191  PA_000002, PA_000004, PA_000009    3
PO_001045MSP2526                        PA_000001    2

Note: if reference column is numeric, ', '.join will not work. In such case, use lambda x: ', '.join(str(i) for i in x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM