如何在总数据中查找唯一项

2024-04-24 23:06:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大约60000行的数据集。这是一个您没有唯一ID的采购订单。下面是示例数据。你知道吗

36 40 41 42 43 45 46
38 39 48 50 51 57
41 59 62
63 66 67 68
74 75 76 77

在上面的列表中,每个号码都是购买的商品。我需要以下信息:

  1. 数据集中唯一项的总数。你知道吗
  2. 购买最多的前5项。你知道吗

Tags: 数据订单信息id示例列表商品号码
3条回答

这应该做到:

from collections import Counter

items = Counter()
with open('data_file.txt', 'r') as f:
    for line in f:
        items.update(line.split())

print("Total Unique Items: {0}".format(len(items)))

for item, count in items.most_common(5):
    print("Item {0} was purchased {1} times".format(item, count))

是的,就那么短:)。你知道吗

要获得列表的总长度,请使用循环遍历行,并使用list.append(x)将每个整数添加到Python列表中,条件是if x not in list以消除重复项。然后,使用list.sort()对列表进行排序。最后,做len(list)。你知道吗

要获得购买量最大的前5个项目,再次使用循环遍历行,但这次将所有整数添加到列表中,而不考虑重复项。然后做collections.Counter(list).most_common(5)[0][0]。你知道吗

请参见Python列表文档here和集合文档here。你知道吗

假设数据集是csv文件或文本文件。你知道吗

from collections import Counter

with open(path, "r") as fp:
    raw = fp.readlines()

purchases = [item for line in raw for item in line.split()]
print "Unique ids: %s" %(len(set(purchases))
print "Most purchased ids:" %(",".join([ item[1] for item in Counter(purchases).most_common(5)]))

上面的代码应该给出您的结果。你知道吗

希望有帮助。你知道吗

相关问题 更多 >