在pandas中实现Apriori算法的最佳方法是什么?我目前在使用for循环提取模式时遇到了困难。从for循环开始的部分都不起作用。是否有在pandas中使用向量化方法来实现这一点的方法?
import pandas as pdimport numpy as nptrans=pd.read_table('output.txt', header=None,index_col=0)def apriori(trans, support=4): ts=pd.get_dummies(trans.unstack().dropna()).groupby(level=1).sum() #用户输入 collen, rowlen =ts.shape #项目最大长度 tssum=ts.sum(axis=1) maxlen=tssum.loc[tssum.idxmax()] items=list(ts.columns) results=[] #遍历项目 for c in range(1, maxlen): #生成模式 pattern=[] for n in len(pattern): #计算支持度 pattern=['supp']=pattern.sum/rowlen #按支持度级别过滤 Condit=pattern['supp']> support pattern=pattern[Condit] results.append(pattern) return resultsresults =apriori(trans)print results
当我插入支持度为3的数据时
a b c d e0 11 1 1 1 0 0666 1 0 0 1 110101 0 1 1 1 01010 1 1 1 1 0414147 0 1 1 0 010101 1 1 0 1 01242 0 0 0 1 1101 1 1 1 1 0411 0 0 1 1 1444 1 1 1 0 0
输出应该类似于
Pattern support a 6 b 7 c 7 d 7 e 3 a,b 5 a,c 4 a,d 4
回答:
假设我理解了你的需求,也许
from itertools import combinationsdef get_support(df): pp = [] for cnum in range(1, len(df.columns)+1): for cols in combinations(df, cnum): s = df[list(cols)].all(axis=1).sum() pp.append([",".join(cols), s]) sdf = pd.DataFrame(pp, columns=["Pattern", "Support"]) return sdf
可以帮助你开始:
>>> s = get_support(df)>>> s[s.Support >= 3] Pattern Support0 a 61 b 72 c 73 d 74 e 35 a,b 56 a,c 47 a,d 49 b,c 610 b,d 412 c,d 414 d,e 315 a,b,c 416 a,b,d 321 b,c,d 3[15 rows x 2 columns]