2 回答

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
groupby兩次。第一個(gè)獲得每個(gè)的總和['InvoiceNo', 'ItemCode']。然后我們將代碼和類別與“-”連接在一起,并對(duì)發(fā)票進(jìn)行分組以創(chuàng)建完整的字符串。
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
你會(huì)注意到我不需要整理任何東西。這是因?yàn)間roupby默認(rèn)情況下對(duì)分組鍵進(jìn)行排序,所以在第一行之后系列保證按 排序['InvoiceNo', 'ItemCode'],這是我們之前想要的', '.join

TA貢獻(xiàn)1934條經(jīng)驗(yàn) 獲得超2個(gè)贊
干得好:
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-1
添加回答
舉報(bào)