我有一个数据框如下
+-----------+----------+-----+
| 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明智项目组合。即每个的总和ItemCode。排序并连接到一个字符串。注意:在Inv-002产品中a有 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
df = pd.read_excel('data.xlsx')
#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 |
+---+---------------------+
请指导我解决这个问题。
Cats萌萌
撒科打诨
相关分类