【问题标题】:Finding most and least frequent rows of a text file in python在python中查找文本文件中最频繁和最不频繁的行
【发布时间】:2018-10-01 08:19:04
【问题描述】:

我有一个文本文件,其中只有一列包含文本内容。我想找出前 3 个最频繁的项目和 3 个最不频繁的项目。我在其他帖子中尝试了一些解决方案,但我无法得到我想要的。我尝试找到如下所示的模式,但它只输出所有行。我也尝试使用计数器和最常用的功能,但它们做同样的事情,即打印文件中的所有行。任何帮助表示赞赏。

# My Code

import pandas as pd

df = pd.read_csv('sample.txt')

print(df.mode())

【问题讨论】:

标签: python pandas counter mode


【解决方案1】:

可以使用 Python 内置的counter

from collections import Counter

# Read file directly into a Counter
with open('file') as f:
    cnts = Counter(l.strip() for l in f)

# Display 3 most common lines
cnts.most_common(3)

# Display 3 least common lines
cnts.most_common()[-3:]

【讨论】:

  • @tdelaney 好建议!我已将其纳入我的答案中
猜你喜欢
  • 1970-01-01
  • 2013-11-27
  • 2021-04-21
  • 1970-01-01
  • 2017-04-22
  • 2020-11-23
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多