簡體   English   中英

在數據集中查找最頻繁的項目

[英]Finding the most frequent items in a dataset

我正在使用大型數據集,因此我只想使用最常使用的項目。

數據集的簡單示例:

1 2 3 4 5 6 7
1 2
3 4 5
4 5
4
8 9 10 11 12 13 14
15 16 17 18 19 20

4次出現4次,
1次出現2次,
2次出現2次,
5次出現2次,

我希望能夠僅使用最頻繁的項目(在本例中為最常見的4種)來生成新的數據集:

想要的結果:

1 2 3 4 5
1 2
3 4 5
4 5
4

我找到了前50個最常見的項目,但是我沒有以正確的方式將它們打印出來。 (我的輸出結果是相同的數據集)

這是我的代碼:

 from collections import Counter

with open('dataset.dat', 'r') as f:
    lines = []
    for line in f:
        lines.append(line.split())
    c = Counter(sum(lines, []))
    p = c.most_common(50);

with open('dataset-mostcommon.txt', 'w') as output:
    ..............

有人可以幫我實現目標嗎?

您必須再次迭代數據集,並且對於每一行,僅顯示最常見數據集的那些數據集。

如果輸入行已排序,則可以設置交集並按排序順序打印它們。 如果不是,則迭代行數據並檢查每個項目

for line in dataset:
    for element in line.split()
        if element in most_common_elements:
            print(element, end=' ')
    print()

PS:對於Python 2,在腳本頂部from __future__ import print_function添加

根據文檔, c.most-common返回一個元組列表,您可以獲得以下期望的輸出:

with open('dataset-mostcommon.txt', 'w') as output:
    for item, occurence in p:
        output.writelines("%d has %d occurrences,\n"%(item, occurence))

暫無
暫無

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

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