I have a dataframe as below
+-----------+----------+-----+
| 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 |
+-----------+----------+-----+
I want to calculate each individual InvoiceNo wise item combinations. i.e. sum of each ItemCode. sorted and concatenated to one string.
Note : in Inv-002 product a has 2 lines.
My desired/required output is as below
+-----------+--------------------+
| 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 |
+-----------+--------------------+
so far I have written the below code
#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]
below is the result I get. all the items separated.
+---+---------------------+
| 0 | a,b,b,c |
+---+---------------------+
| 1 | a,a,a,a,b,c,d,d,d,d |
+---+---------------------+
| 2 | b,b,e |
+---+---------------------+
please guide me to solve this.