# 熊猫Groupby sum和concatenate

``````+-----------+----------+-----+
| InvoiceNo | ItemCode | Qty |
+-----------+----------+-----+
|  Inv-001  |     c    |  1  |
+-----------+----------+-----+
|  Inv-001  |     b    |  2  |
+-----------+----------+-----+
|  Inv-001  |     a    |  1  |
+-----------+----------+-----+
|  Inv-002  |     a    |  3  |
+-----------+----------+-----+
|  Inv-002  |     b    |  1  |
+-----------+----------+-----+
|  Inv-002  |     c    |  1  |
+-----------+----------+-----+
|  Inv-002  |     d    |  4  |
+-----------+----------+-----+
|  Inv-002  |     a    |  1  |
+-----------+----------+-----+
|  Inv-003  |     e    |  1  |
+-----------+----------+-----+
|  Inv-003  |     b    |  2  |
+-----------+----------+-----+
``````

``````+-----------+--------------------+
| InvoiceNo |   Desired result   |
+-----------+--------------------+
|  Inv-001  |    a-1, b-2, c-1   |
+-----------+--------------------+
|  Inv-002  | a-4, b-1, c-1, d-4 |
+-----------+--------------------+
|  Inv-003  |      b-2, e-1      |
+-----------+--------------------+
``````

``````#load data

#groupby and sum
g = df.groupby(['InvoiceNo','ItemCode']).sum()

# Codes to convert the MultiIndex to a regualr dataframe
g = g.unstack(fill_value=0)
g.reset_index(drop=True,inplace=True)
g = g.droplevel(level=0, axis=1).fillna(0)

#calculation
g.dot(g.columns+',').str[:-1]
``````

``````+---+---------------------+
| 0 |       a,b,b,c       |
+---+---------------------+
| 1 | a,a,a,a,b,c,d,d,d,d |
+---+---------------------+
| 2 |        b,b,e        |
+---+---------------------+
``````

ALollz：

`groupby`两次。第一个得到每个的和`['InvoiceNo', 'ItemCode']`然后，将代码和类别与“-”连接在一起，并在发票上分组以创建完整的字符串。

``````df1 = df.groupby(['InvoiceNo', 'ItemCode'])['Qty'].sum().reset_index('ItemCode')

df1 = df1['ItemCode'].str.cat(df1['Qty'].astype(str), '-').groupby(level=0).agg(', '.join)

#InvoiceNo
#Inv-001         a-1, b-2, c-1
#Inv-002    a-4, b-1, c-1, d-4
#Inv-003              b-2, e-1
#Name: ItemCode, dtype: object
``````

0 条评论