Python Pandas统计最常出现的事件

时间:2018-12-10 13:22:36

标签: python pandas count frequency frequency-analysis

这是我的示例数据框,其中包含有关订单的数据:

import pandas as pd
my_dict = { 
     'status' : ["a", "b", "c", "d", "a","a", "d"],
     'city' : ["London","Berlin","Paris", "Berlin", "Boston", "Paris", "Boston"],
     'components': ["a01, a02, b01, b07, b08, с03, d07, e05, e06", 
                    "a01, b02, b35, b68, с43, d02, d07, e04, e05, e08", 
                    "a02, a05, b08, с03, d02, d06, e04, e05, e06", 
                    "a03, a26, a28, a53, b08, с03, d02, f01, f24", 
                    "a01, a28, a46, b37, с43, d06, e04, e05, f02", 
                    "a02, a05, b35, b68, с43, d02, d07, e04, e05, e08", 
                    "a02, a03, b08, b68, с43, d06, d07, e04, e05, e08"]
}
df = pd.DataFrame(my_dict)
df

enter image description here

我需要计数一次:

  1. 订单中的前n个同时出现的组件
  2. 最常见的前n个组件(无论是否同时出现)

什么是最好的方法?

我也可以看到与购物篮分析问题的关系,但不确定如何做。

2 个答案:

答案 0 :(得分:2)

@ScottBoston的答案显示了矢量化的方法(因此可能更快)。

发生率最高的

from collections import Counter
from itertools import chain

n = 3
individual_components = chain.from_iterable(df['components'].str.split(', '))
counter = Counter(individual_components)
print(counter.most_common(n))
# [('e05', 6), ('e04', 5), ('a02', 4)]


前n名同时发生

请注意,我使用n两次,一次用于“共现的大小”,一次用于“ top-n”部分。显然,您可以使用2个不同的变量。

from collections import Counter
from itertools import combinations

n = 3
individual_components = []
for components in df['components']:
    order_components = sorted(components.split(', '))
    individual_components.extend(combinations(order_components, n))
counter = Counter(individual_components)
print(counter.most_common(n))
# [(('e04', 'e05', 'с43'), 4), (('a02', 'b08', 'e05'), 3), (('a02', 'd07', 'e05'), 3)]

答案 1 :(得分:2)

以下是做同一件事的更多“熊猫”方式:

要获取前三个组成部分

#Using list comprehension usually faster than .str accessor in pandas
pd.concat([pd.Series(i.split(',')) for i in df.components]).value_counts().head(3)
#OR using "pure" pandas methods
df.components.str.split(',', expand=True).stack().value_counts().head(3)

输出:

 e05    6
 e04    5
 d02    4
dtype: int64

接下来找到同类群组,总共报告了3个组成部分,n = 3:

from itertools import combinations
n=3
pd.concat([pd.Series(list(combinations(i.split(','), n))) for i in df.components])\
  .value_counts().head(3)

输出:

( с43,  e04,  e05)    4
(a02,  e04,  e05)     3
( с43,  d07,  e05)    3
dtype: int64