![](/img/trans.png)
[英]Python - pandas - find most frequent combination with tie-resolution - performance
[英]Python: How to find most frequent combination of elements?
機器提供熊貓數據幀中提供的故障代碼。 id
標識機器, code
為故障代碼:
df = pd.DataFrame({
"id": [1,1,1,1,1,2,2,2,2,3,3,3,3,3,3,4],
"code": [1,2,5,8,9,2,3,5,6,1,2,3,4,5,6,7],
})
閱讀示例:機器 1 生成了 5 個代碼:1、2、5、8 和 9。
我想找出所有機器上最常見的代碼組合。 該示例的結果將類似於[2]
(3x)、 [2,5]
(3x)、 [3,5]
(2x) 等。
我怎樣才能做到這一點? 由於有大量數據,我正在尋找有效的解決方案。
以下是表示數據的另外兩種方法(以防計算更容易):
pd.crosstab(df.id, df.code)
df.groupby("id")["code"].apply(list)
使用自定義函數all_subsets
,然后按Series.explode
壓平值,最后使用Series.value_counts
:
from itertools import chain, combinations
#https://stackoverflow.com/a/5898031
#only converted to list and removed empty tuples by range(1,...
def all_subsets(ss):
return list(chain(*map(lambda x: combinations(ss, x), range(1, len(ss)+1))))
s = df.groupby('id')['code'].apply(all_subsets).explode().value_counts()
print (s)
(2,) 3
(2, 5) 3
(5,) 3
(1, 2) 2
(3, 6) 2
..
(1, 5, 8) 1
(9,) 1
(1, 3, 4, 6) 1
(5, 8, 9) 1
(4, 6) 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.