I have created a logic, which is counting how many people bought the same products. It works, but it is really inefficient (running out of memory the whole time).
Therefore, I hope that someone has a logic which is less memory consuming than mine.
This is what I have done:
df: # Please note: below you can find the code to duplicate this.
Order_Number Country Product
1 Ger [A,B]
2 NL [A,B,C]
3 USA [C,D]
4 NL [B,C,D]
5 GER [A]
I would like to know how many customers bought the same products (with a minimum of two products obviously):
list_df = [df]
# Example for two products bought together
for X in list_df : #
#print(X)
combinations_list = []
for row in X.Product:
combinations = list(itertools.combinations(row, 2)) # Only counting for 2 products here
combinations_list.append(combinations)
Products_DF = pd.Series(combinations_list).explode().reset_index(drop=True)
Products_DF = Products_DF.value_counts()
Products_DF = Products_DF.to_frame()
Products_DF.reset_index(level=0, inplace=True)
Products_DF = Products_DF.rename(index = str, columns = {"index":"Product"})
Products_DF = Products_DF.rename(index = str, columns = {0:"Occurrence"})
Products_DF['Product_Combinations'] = 2 # Only counting for 2 products here
Products_DF['Country'] = X['Country']
main_dataframe = main_dataframe.append(Products_DF, ignore_index = True)
del(Products_DF)
Then, I redo the above again for 3,4,5,6 and 7 products bought together. Having all information appended in my main_dataframe.
The result is one dataframe, containing the country, products bought together and the occurrence. Just as the output from the data below.
Many thanks in advance!
PS I'm also open for PySpark solutions (everything is appreciated!)
Complete example:
import pandas as pd
import itertools
df= {'Order_Number':['1', '2', '3', '4', '5'],
'Country':['Ger', 'NL', 'USA', 'NL', 'Ger'],
'Product': ['[A,B]', '[A,B,C]','[C,D]', '[B,C,D]', '[A]']}
# Creates pandas DataFrame.
df = pd.DataFrame(df)
df = [df] # sorry, this is legacy in my code
main_dataframe = pd.DataFrame()
# Example for two products bought together
for X in df : #
#print(X)
combinations_list = []
for row in X.Product:
combinations = list(itertools.combinations(row, 2)) # Only counting for 2 products here
combinations_list.append(combinations)
Products_DF = pd.Series(combinations_list).explode().reset_index(drop=True)
Products_DF = Products_DF.value_counts()
Products_DF = Products_DF.to_frame()
Products_DF.reset_index(level=0, inplace=True)
Products_DF = Products_DF.rename(index = str, columns = {"index":"Product"})
Products_DF = Products_DF.rename(index = str, columns = {0:"Occurrence"})
Products_DF['Product_Combinations'] = 2 # Only counting for 2 products here
Products_DF['Country'] = X['Country']
main_dataframe = main_dataframe.append(Products_DF, ignore_index = True)
del(Products_DF)