import pandas as pd
from apyori import apriori


def Apriori():
    # Data Preprocessing
    data = pd.read_csv('Market_Basket_Optimisation.csv', header=None)
    transactions = []
    for i in range(len(data)):   #for i in range(0, 7501):
        transactions.append([str(data.values[i, j]) for j in range(len(data.columns))])  #for j in range(0, 20)

    # Training the Apriori model on the dataset
    rules = apriori(transactions=transactions, min_support=0.003, min_confidence=0.2, min_lift=3, min_length=2, max_length=2)

    # Displaying the first results coming directly from the output of the apriori function
    results = list(rules)

    # Putting the results well organised into a pandas DataFrame
    def inspect(results):
        lhs = [tuple(result[2][0][0])[0] for result in results]
        rhs = [tuple(result[2][0][1])[0] for result in results]
        supports = [result[1] for result in results]
        confidences = [result[2][0][2] for result in results]
        lifts = [result[2][0][3] for result in results]
        return list(zip(lhs, rhs, supports, confidences, lifts))
    resultsinDataFrame = pd.DataFrame(inspect(results), columns=['Left Hand Side', 'Right Hand Side', 'Support', 'Confidence', 'Lift'])

    # Displaying the results non sorted
    print(resultsinDataFrame, '\n')
    # Displaying the results sorted by descending lifts
    print(resultsinDataFrame.nlargest(n=10, columns='Lift'))

if __name__ == '__main__':
    Apriori()


