Python - 如何按频率检查数字组合

Python - How to check the combination of numbers by frequency

让我们以下面的数据为例。

 h: [Num1, Num2, Num3, Num4, Num5, Num6]
 a: [1,       2,    3,    4,    5,    6]
 b: [1,       2,    7,    8,    9,   10]
 c: [1,       2,    3,    6,    8,   10]

现在,假设我想查看按频率排序的 2+ 的组合。

我们以number:1为例,它出现在我们的a、b、c三行中。

当 1 被“使用”时,它通常与 2 (3/3) 配对,然后是 3、6、8、10 (2/3)。 换句话说,当 1 被“使用”时,它可能看起来像这样:

 [1, 2, x, y, z, t]
 [1, 2, 3, x, y, z]
 [1, 2, 6, x, y, z]
 .
 .
 .
 [1, 8, x, y, z, t]
 [1, 10, x, y, z, t]
 [1, 2, 3, 6, 8, 10]

顺序无关紧要。 x, y, z, t 可以是任何给定的数字。重复项不是 present/allowed.

我有一个采用这种格式的数据框,想看看还有哪些其他整数与 44 组合在一起。

例如:

 44 was paired with 11, 350 times out of 2000
 44 was paired with 27, 290 times out of 2000
 44 was paired with 35, 180 times out of 2000
 .
 .
 .
 44 was paired with 2, 5 times out of 2000

我知道每列中每个数字出现的频率,我只是不知道如何继续这个。

期待想法和问题。 谢谢!

您可以使用 itertools 模块中的 Counter

from itertools import combinations
from collections import Counter
data = [[1, 2, 3],[1, 2, 5],[1, 3, 8],[2, 5, 8]]
pairings = Counter(
    pair for row in data 
    for pair in combinations(sorted(row), 2)
)

Counter 对象类似于字典。

Counter({
    (1, 2): 2, 
    (1, 3): 2, 
    (2, 5): 2, 
    (2, 3): 1, 
    (1, 5): 1, 
    (1, 8): 1, 
    (3, 8): 1, 
    (2, 8): 1, 
    (5, 8): 1
})

您可以像这样获得特定对的计数:

>>> pairings[1,2] 
2