gpt4 book ai didi

python - 计算给定数据框中项集的频率

转载 作者:行者123 更新时间:2023-12-04 13:29:05 25 4
gpt4 key购买 nike

我有以下数据框,

data = pd.read_csv('sample.csv', sep=',')
Dataframe
我需要搜索集合中存在的项集的频率。例如: itemsets = {(143, 157), (143, 166), (175, 178), (175, 190)}这应该搜索数据帧中每个元组的频率(尝试实现 Apriori 算法)。我在如何单独处理数据框中的元组以及搜索元组而不是数据中的单个条目方面遇到了特别的麻烦。
更新 1
例如数据框是这样的:
39, 120, 124, 205, 401, 581, 704, 814, 825, 834
35, 39, 205, 712, 733, 759, 854, 950
39, 422, 449, 704, 825, 857, 895, 937, 954, 964
更新 2
仅当该元组中的所有值都存在于特定行中时,函数才应增加该元组的计数。
例如,如果我搜索 (39, 205) ,它应该返回 2 的频率,因为其中 2 行同时包含 39205 (第一行和第二行)。

最佳答案

此函数将返回一个字典,其中包含数据框整个行中元组计数的出现次数。

from collections import defaultdict
def count(df, sequence):
dict_data = defaultdict(int)
shape = df.shape[0]
for items in sequence:
for row in range(shape):
dict_data[items] += all([item in df.iloc[row, :].values for item in items])
return dict_data
您可以将数据框和集合传递给 count()函数,它将为您返回数据框整行中元组的出现次数,即
>>> count(data, itemsets)
defaultdict(<class 'int'>, {(39, 205): 2})
您可以从 defaultdict 轻松更改它使用 dict() 到字典方法,即
>>> dict(count(data, itemsets))
{(39, 205): 2}
但他们两个仍然工作相同。

关于python - 计算给定数据框中项集的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66295267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com