首页 > 解决方案 > 使用 pandas 计算集合中项目的出现次数

问题描述

如何在 Python 中使用 Pandas 计算项目的出现次数和项目集中的所有组合。我尝试使用 Apriori 算法,但我可以用于最小支持的最小值是 0.1。还有另一种方法可以做到这一点吗?

frequent_itemsets = apriori(df_rules_nf, min_support=0.3, use_colnames=True)
frequent_itemsets['length'] = frequent_itemsets['itemsets'].apply(lambda x: len(x))
frequent_itemsets

我的输入数据框如下所示:

df('Rules')= 
a|b|c
c
a
a|b
b|c

输出:

df_out=
Combos Occurrenecs
a        3/5
b        3/5
c        3/5
a,b      2/5
b,c      2/5
a,c      1/5

上面的输出表示项目一起或单独看到的次数/事件总数。出现次数可以是十进制格式。

例如:“a”在 5 个事件中出现 3 次,而 a、b 在 5 个事件中出现 2 次。

标签: pythonpandasdataframe

解决方案


这是一种使用方式itertools.combinations和字典理解。但是在使用之前需要对str.get_dummies| 进行拆分 到不同的列。

# input 
s = pd.Series({0: 'a|b|c', 1: 'c', 2: 'a', 3: 'a|b', 4: 'b|c'})

# expand to dataframe
df_dum = s.str.get_dummies().astype(bool)
print(df_dum)
       a      b      c
0   True   True   True
1  False  False   True
2   True  False  False
3   True   True  False
4  False   True   True

然后你对可能性中每个长度的每个组合都做所有事情,并沿着列使用

from itertools import combinations

d_ = {','.join(cols): # to get index as shown
      df_dum[list(cols)].all(axis=1).sum() # get the number of rows with 
                                      # all True in the col combination
      for i in range(1, df_dum.shape[1]+1) # different length of combination
      for cols in combinations(df_dum.columns, i)} # all different combinations length i

res = pd.Series(d_)
print(res)
a        3
b        3
c        3
a,b      2
a,c      1
b,c      2
a,b,c    1
dtype: int64

我会保留这样的结果,但是为了适合您的预期输出,您可以这样做

res = res.astype(str) + f'/{len(s)}'
print(res)
a        3/5
b        3/5
c        3/5
a,b      2/5
a,c      1/5
b,c      2/5
a,b,c    1/5
dtype: object

请注意,如果您没有太多不同的值作为输入,这种方式很有趣


推荐阅读