【问题标题】:Counting the number of pairs of items in a grouped dataframe's column. (Pandas)计算分组数据框列中的项目对数。 (熊猫)
【发布时间】:2020-05-27 07:59:00
【问题描述】:

我想计算一列中项目对的数量。我为此制定了解决方案,但我想知道是否有更简洁的解决方案。

这是一个例子和我的方法。 我有一个像这样的数据框。

df = pd.DataFrame({'id':[1,1,2,2], 'item':['apple','orange','orange','apple']})

最后,我想知道一起购买最多的物品是什么。因此,在这种情况下,我想得到橙子和苹果一起购买最多的结果。

然后,我根据id 列中的值进行分组。

id_group = df.groupby('id')

然后,为了计算item 列中的项目对数,我制作了如下所示的函数并将其应用于id_groupitem 列。在此之后,我使用sum() 组合了元组列表。最后,我使用Counter() 来计算包含相同项目的对数。 在combos() 中,我使用sorted() 来避免分别计算('apple','orange')('orange','apple')

是否有更好的方法来获得显示有 2 对 ('apple','orange') 或 2 对 ('orange','apple') 的结果

import itertools 
from collections import Counter
def combos(x):
     combinations = []
     num = x.size
     while num != 1:
          combinations += list(itertools.combinations(x,num))
          num -= 1
     element_sorted = map(sorted,combinations)
     return list(map(tuple,element_sorted))

k= id_group['item'].apply(lambda x:combos(x)).sum()
Counter(k)

【问题讨论】:

    标签: python pandas combinations


    【解决方案1】:

    使用 all_subsets 函数并将 0 更改为 2 用于配对、三重...就像您的解决方案:

    #https://stackoverflow.com/a/5898031
    from itertools import chain, combinations
    def all_subsets(ss):
        return chain(*map(lambda x: combinations(ss, x), range(2, len(ss)+1)))
    

    然后展平值,我认为最好不要使用sum 来连接列表。它看起来很花哨,但它是二次的,应该被认为是不好的做法。

    所以这里在列表理解中使用排序元组进行展平:

    k = [tuple(sorted(z)) for y in id_group['item'].apply(all_subsets) for z in y]
    
    print (Counter(k))
    Counter({('apple', 'orange'): 2})
    

    【讨论】:

    • 非常感谢您非常有帮助的回答!我真的很感激。
    • @Sherlock_Hound - 解决方案未被接受,有问题吗?
    • 我很抱歉搞砸了。我猜想列表理解中的sorted(y) 不会改变元组中项目的顺序。当我运行代码时,我仍然得到Counter({('apple', 'orange'): 1, ('orange', 'apple'): 1})
    • @Sherlock_Hound - 你是对的,抱歉,已编辑答案。
    • 您不必感到抱歉。你所做的真的很有帮助!我没有真正运行你的代码是我的错。谢谢!
    【解决方案2】:

    这个怎么样?

    from collections import Counter
    k = df.groupby('id')['item'].apply(lambda x: tuple(x.sort_values()))
    Counter(k)
    
    Counter({('apple', 'orange'): 2})
    

    【讨论】:

    • 我想你提到你不确定我想做什么。对于那个很抱歉。我稍微编辑了我的问题。我希望它会有所帮助。我非常感谢您的贡献。
    • Np,我认为@Jezrael 的解决方案是可行的方法:-)
    猜你喜欢
    • 2015-01-28
    • 1970-01-01
    • 2021-12-23
    • 2023-02-20
    • 2021-06-08
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多