簡體   English   中英

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+ 組合。

我們以數字: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

我有每列中每個數字出現的頻率,我只是不知道如何繼續這個。

期待想法和問題。 謝謝!

您可以使用 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)
)

計數器 object 類似於字典。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM