这段代码主要利用 Apriori 算法进行关联分析,以找出销售流水明细数据中的品类和单品之间的关联规则。

首先,通过 pandas 库读取销售流水明细数据,并将商品信息与销售流水明细数据合并。

然后,根据品类和单品对销售数量进行汇总。

接下来,定义一个函数 encode_units,用于将销售量转换为二进制编码。

然后,使用 Apriori 算法分别对品类和单品的销售量进行关联分析。这里使用的参数包括最小支持度 (min_support) 为 0.1,即频繁项集出现的最小比例为 0.1;使用列名 (use_colnames) 为 True,即使用实际的列名而不是索引。

最后,通过调用 association_rules 函数,根据关联分析的结果计算关联规则。这里使用的参数包括度量 (metric) 为 'lift',即使用提升度来衡量关联规则的强度;最小阈值 (min_threshold) 为 1,即只保留提升度大于等于 1 的关联规则。

最后,打印出品类之间和单品之间的关联规则。

总结起来,这段代码的目的是通过关联分析找出销售流水明细数据中的品类和单品之间的关联规则,以帮助企业了解不同品类或单品之间的关联关系,从而进行相应的销售策略调整或推荐系统的构建。

import pandas as pd
from mlxtend.frequent_patterns import apriori
from mlxtend.frequent_patterns import association_rules

# 读取销售流水明细数据
sales_data = pd.read_excel('附件2.xlsx')

# 进行数据处理,将商品信息与销售流水明细数据合并
merged_data = pd.merge(sales_data, 商品信息表, on='商品ID')

# 根据品类或单品进行销售量汇总
category_sales = merged_data.groupby('品类')['销售数量'].sum()
item_sales = merged_data.groupby('单品')['销售数量'].sum()

# 将销售量转换为二进制编码
def encode_units(x):
    if x <= 0:
        return 0
    if x >= 1:
        return 1

category_sales_encoded = category_sales.apply(encode_units)
item_sales_encoded = item_sales.apply(encode_units)

# 使用 Apriori 算法进行关联分析
frequent_itemsets_category = apriori(category_sales_encoded, min_support=0.1, use_colnames=True)
rules_category = association_rules(frequent_itemsets_category, metric='lift', min_threshold=1)

frequent_itemsets_item = apriori(item_sales_encoded, min_support=0.1, use_colnames=True)
rules_item = association_rules(frequent_itemsets_item, metric='lift', min_threshold=1)

# 打印关联规则
print('品类之间的关联规则:')
print(rules_category)
print('
单品之间的关联规则:')
print(rules_item)
Python Apriori 关联规则分析:挖掘销售数据中的关联关系

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

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