import pandas as pd
import time

#数据加载
data = pd.read_csv("project1_BreadBasket_DMS.csv")
#print(data.shape)
#print(data.head())

#item统一小写
data["Item"] = data["Item"].str.lower()

#去掉item中的none项
data = data.drop(data[data["Item"] == "none"].index)

#采用apriori挖掘关联规则
def rule1():
    from efficient_apriori import apriori
    start = time.time()
    #将Transaction作为index,Item作为value生成待分析数据
    orders_series = data.set_index("Transaction")["Item"]
    #将数据集进行格式转换
    transactions = []
    temp_index = 0
    for i,v in orders_series.items():
        if i !=  temp_index:
            temp_set = set()
            temp_index = i
            temp_set.add(v)
            transactions.append(temp_set)
        else:
            temp_set.add(v)
    #挖掘频繁项集和频繁规则
    itemsets,rules = apriori(transactions,min_support = 0.02,min_confidence= 0.5)
    print("频繁项集：",itemsets)
    print("关联规则",rules)
    end = time.time()
    print("用时：",end - start)

def encode_units(x):
    if x <= 0:
        return 0
    if x >= 1:
        return 1

def rule2():
    from mlxtend.frequent_patterns import apriori
    from mlxtend.frequent_patterns import association_rules

    pd.options.display.max_columns = 100
    start = time.time()
    hot_encoded_df = data.groupby(["Transaction","Item"])["Item"].count().unstack().reset_index().fillna(0).set_index("Transaction")
    #print(hot_encoded_df)
    hot_encoded_df = hot_encoded_df.applymap(encode_units)
    frequencey_itemsets = apriori(hot_encoded_df, min_support= 0.02, use_colnames= True)
    rules = association_rules(frequencey_itemsets, metric="lift", min_threshold= 0.5)
    print("频繁项集：",frequencey_itemsets)
    print("关联规则：",rules[(rules["lift"] >= 1) & (rules["confidence"] >= 0.5)])
    end = time.time()
    print("用时：",end - start)

#rule1()
rule2()







