import pandas as pdfrom mlxtendfrequent_patterns import apriorifrom mlxtendfrequent_patterns import association_rules# 读取附件1和附件2的数据df_products = pdread_excel附件1xlsxdf_sales = pdread_excel附件2xlsx# 合并商品
导入pandas库
import pandas as pd
导入mlxtend库中的apriori和association_rules函数
from mlxtend.frequent_patterns import apriori from mlxtend.frequent_patterns import association_rules
读取附件1和附件2的数据
df_products = pd.read_excel('附件1.xlsx') # 读取附件1的数据,存储为DataFrame对象df_products df_sales = pd.read_excel('附件2.xlsx') # 读取附件2的数据,存储为DataFrame对象df_sales
合并商品信息和销售数据
df_merged = df_sales.merge(df_products, on='单品编码', how='inner') # 根据单品编码将附件2的数据与附件1的数据进行合并,存储为DataFrame对象df_merged
创建交易数据表
basket = pd.pivot_table(df_merged, index='销售日期', columns='单品名称', values='销量', aggfunc='sum', fill_value=0) # 根据销售日期和单品名称创建交易数据表,其中值为销量,使用sum函数对重复值进行求和,缺失值填充为0
使用Apriori算法挖掘频繁项集
frequent_itemsets = apriori(basket, min_support=0.1, use_colnames=True) # 使用Apriori算法挖掘频繁项集,其中最小支持度为0.1,设置use_colnames为True表示使用列名而不是索引值
根据频繁项集生成关联规则
rules = association_rules(frequent_itemsets, metric='lift', min_threshold=1.0) # 根据频繁项集生成关联规则,其中使用lift作为评估指标,最小阈值为1.0
打印频繁项集和关联规则
print("频繁项集:") print(frequent_itemsets) # 打印频繁项集
print("\n关联规则:") print(rules) # 打印关联规则
原文地址: http://www.cveoy.top/t/topic/i1ne 著作权归作者所有。请勿转载和采集!