我有如下所示的数据
+-----------+----------+-----+
| 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 |
+---+---------------------+请指导我解决这个问题。
发布于 2020-07-24 18:00:40
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你会注意到我不需要整理任何东西。这是因为在默认情况下,groupby对分组键进行排序,所以在第一行之后,将保证在['InvoiceNo', 'ItemCode']上对该系列进行排序,这是我们在', '.join之前所希望的
发布于 2020-07-24 18:22:30
给你:
df1 = df.groupby(['InvoiceNo', 'ItemCode'], sort=False).Qty.sum().reset_index()
df1['Desired result'] = df1.ItemCode + '-' + df1.Qty.astype(str)
print(df1.groupby(['InvoiceNo'])['Desired result'].apply(lambda res: ', '.join(sorted(res))).reset_index())输出:
InvoiceNo Desired result
0 Inv-001 a-1, b-2, c-1
1 Inv-002 a-4, b-1, c-1, d-4
2 Inv-003 b-2, e-1https://stackoverflow.com/questions/63078869
复制相似问题