I have the following dataset:
import pandas as pd
from itertools import combinations
d = {'Order_ID': ['001', '001', '002', '003', '003', '003', '004', '004'],
'Products': ['Apple', 'Pear', 'Banana', 'Apple', 'Pear', 'Banana', 'Apple', 'Pear'],
'Revenue': [15, 10, 5, 25, 15, 10, 5, 30]}
df = pd.DataFrame(data=d)
df
Yielding:
Order_ID Products Revenue
0 001 Apple 15
1 001 Pear 10
2 002 Banana 5
3 003 Apple 25
4 003 Pear 15
5 003 Banana 10
6 004 Apple 5
7 004 Pear 30
What I'm trying to achieve is a dataset that has all the possible combinations of pairs found in all transactions, get their frequency and the running sum of the revenue. It should look something like this:
d = {'Groups': ['(Apple, Pear)', '(Banana, Apple)', '(Banana, Pear)'],
'Frequency': [3, 1, 1],
'Revenue': [100, 35, 40]}
df2 = pd.DataFrame(data=d)
df2
Which returns:
Groups Frequency Revenue
0 (Apple, Pear) 3 100
1 (Banana, Apple) 1 35
2 (Banana, Pear) 1 40
I was able to get the pairs and their frequency, but I can't figure out how to get the revenue part in the groupby statement that I use:
def find_pairs(x):
return pd.Series(list(combinations(set(x), 2)))
df_group = df.groupby('Order_ID')['Products'].apply(find_pairs).value_counts()
df_group
I would need to add another condition after the function is applied to 'Products' in which the 'Revenue' is summed up by these 'new' groups created by the find_pairs function. The revenue must be the overall sum for each pair, that is, for each time that the group is repeated, add the products revenue to the running sum for the group.