1

我想过滤具有关联规则结果的数据框。在我的情况下,我想要包含 H 或 L 之类的元素的先行词。前因是frozenset类型。我试过 Hrules 但它不起作用。

Hrules=fdem_rules['H'  in fdem_rules['antecedents']]
Hrules=fdem_rules[frozenset({'H'})  in fdem_rules['antecedents']] 

不工作

在下面的例子中,我只需要第 46 和 89 行,因为它们有 H.

df = pd.DataFrame({'antecedents': [frozenset({'N', 'M', '60'}), frozenset({'H', 'AorE'}), frozenset({'0-35', 'H', 'AorE', '60'}), frozenset({'AorE', 'M', '60', '0'}), frozenset({'0-35', 'F'})]})
             antecedents
75            (N, M, 60)
46             (H, AorE)
89   (0-35, H, AorE, 60)
103     (AorE, M, 60, 0)
38             (0-35, F)
4

1 回答 1

1
设置/冻结设置方法

您可以使用applyset/frozenset 的方法。这里要检查是否至少存在 H 或 L,可以使用 的否定{'H', 'L'}.isdisjoint

match = {'H', 'L'}
df['H or L'] = ~df['antecedents'].apply(match.isdisjoint)

上面的一个更快的变体是使用列表推导:

match = {'H', 'L'}
df['H or L'] = [not match.isdisjoint(x) for x in df['antecedents']]
爆炸+isin+聚合

另一种选择是explode冻结集,使用并使用+isin聚合结果:groupbyany

match = {'H', 'L'}
df['H or L'] = df['antecedents'].explode().isin(match).groupby(level=0).any()

输出:

>>> df[['antecedents', 'H or L']]
             antecedents  H or L
75            (N, M, 60)   False
46             (H, AorE)    True
89   (0-35, H, AorE, 60)    True
103     (AorE, M, 60, 0)   False
38             (0-35, F)   False
切片匹配的行
match = {'H', 'L'}
idx = [not match.isdisjoint(x) for x in df['antecedents']]
df[idx]

输出:

            antecedents consequents other_cols
46            (H, AorE)         (N)        ...
89  (0-35, H, AorE, 60)         (0)        ...

于 2022-01-05T08:47:01.027 回答