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

点点圈 提交于 2020-01-11 12:02:27

问题


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.


回答1:


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)



来源:https://stackoverflow.com/questions/57424544/pandas-group-by-sum-of-all-the-values-of-the-group-and-another-column-as-comma-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!