导入必要的库

import pandas as pd # 导入pandas库用于数据处理 from mlxtend.frequent_patterns import apriori # 导入mlxtend库中的apriori函数,用于挖掘频繁项集 from mlxtend.frequent_patterns import association_rules # 导入mlxtend库中的association_rules函数,用于生成关联规则

读取数据

df_products = pd.read_excel('附件1.xlsx') # 从附件1.xlsx读取商品信息,存储为DataFrame对象df_products df_sales = pd.read_excel('附件2.xlsx') # 从附件2.xlsx读取销售数据,存储为DataFrame对象df_sales

合并商品信息和销售数据

df_merged = df_sales.merge(df_products, on='单品编码', how='inner') # 基于'单品编码'列合并df_sales和df_products,存储为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,使用列名而不是索引值

根据频繁项集生成关联规则

rules = association_rules(frequent_itemsets, metric='lift', min_threshold=1.0) # 使用lift作为评估指标,最小阈值设置为1.0,生成关联规则

打印结果

print('频繁项集:') print(frequent_itemsets) # 打印挖掘出的频繁项集

print(' 关联规则:') print(rules) # 打印生成的关联规则

Python 关联规则挖掘:Apriori算法实战

原文地址: https://www.cveoy.top/t/topic/eeVB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录