gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:00:07 24 4
gpt4 key购买 nike

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

 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 可以是任何给定的数字。不存在/不允许重复。

我有一个采用这种格式的数据框,想看看还有哪些其他整数与 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

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

期待想法和问题。谢谢!

最佳答案

你可以使用 Counter来自 itertools 模块

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

关于Python - 如何按频率检查数字组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63187784/

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