Apyori无法输出含多元素的关联规则问题求助
解决Apyori关联规则多前置项显示问题
原代码的核心问题是错误拆分了关联规则的项集结构,没有区分前置项集和后置项。Apyori返回的结果里,item[2][0]包含完整规则信息:
item[2][0][0]:前置项集(即关联规则的左半部分)item[2][0][1]:后置项(规则的右半部分)item[2][0][2]:置信度item[2][0][3]:提升度item[1]:支持度
以下是修改后的完整代码,解决多前置项显示问题:
import pandas as pd from apyori import apriori movie_data = pd.read_csv(r"C:\Users\XY\Desktop\movie_dataset.csv", header = None) num_records = len(movie_data) records = [] for i in range(0, num_records): records.append([str(movie_data.values[i,j]) for j in range(0, 20)]) # 清理空值 for idx in range(len(records)): while 'nan' in records[idx]: records[idx].remove('nan') association_rules = apriori(records, min_support=0.0053, min_confidence=0.20, min_lift=3, min_length=2) association_results = list(association_rules) results = [] for item in association_results: support = round(item[1], 5) # 遍历项集对应的所有关联规则 for rule in item[2]: # 拼接多元素前置项为字符串 base_items = ', '.join([str(x) for x in rule[0]]) # 提取后置项 add_item = str(rule[1][0]) confidence = round(rule[2], 5) lift = round(rule[3], 5) results.append((base_items, add_item, support, confidence, lift)) labels = ['When bought','Likely bought as well','Support','Confidence','Lift'] movie_suggestion = pd.DataFrame.from_records(results, columns = labels) print(movie_suggestion)
关键修改点:
- 用
', '.join()将多元素前置项拼接成字符串,解决单元素显示问题 - 遍历
item[2]中的每个规则,确保捕获项集对应的所有关联组合 - 用
round()统一数值精度,避免过长小数 - 简化空值清理的循环逻辑
输出示例:
| When bought | Likely bought as well | Support | Confidence | Lift | |
|---|---|---|---|---|---|
| 5 | Moana, Tomb Rider | Spiderman 3 | 0.00533 | 0.23255 | 0.23255 |
内容的提问来源于stack exchange,提问作者regflori
相关产品推荐
相关产品推荐

