python - 从 CSV 文件中的行计算数字

标签 python csv matplotlib

所以我有这个 csv 文件,一个列看起来像这样:

1022
1040
1042
1035
11728
1036
1022
1040
1042
1035
11728
1036
1022
1040
1042
1035
11728

现在我需要计算数字出现的频率。我需要这个来用 matplotlib 制作图形图片。因此图形将显示一个数字发生了多少(在这种情况下它是一个事件 ID)

到目前为止我只有打印那一行的代码...

my_reader = csv.reader(open(csvpath))
for col in my_reader:
      print col[3]

我如何计算该特定列中的数字出现的频率?

最佳答案

只需创建一个从数字到计数的映射。 collections.Counter() 类使这一切变得最简单:

import collections

counts = collections.Counter()
for row in my_reader:
    counts[row[3]] += 1

使用 collections.defaultdict 也是一种选择:

counts = collections.defaultdict(int)
for row in my_reader:
    counts[row[3]] += 1

或者你可以使用普通的dict:

counts = {}
for row in my_reader:
    counts[row[3]] = counts.get(row[3], 0) + 1

关于python - 从 CSV 文件中的行计算数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13683954/

相关文章:

python-3.x - Pandas 错误: Passing lists with missing labels

python - 用数字和字符串数据绘制直方图?

python - 将元组传递给函数

python - 如何在 python 中创建具有多个列表/数组的数据框

python - 如何比较numpy多维数组的差异?

python - 在 python 中绘制 3 个图表 2 在顶部和底部轴上?

python - 如何使用 matplotlib 在同一个图上绘制多个轨迹

python - 如何通过路径导入python文件?

python - 将 Python 字典写入 CSV,其中键 = 列,值 = 行

php - 自动检测文件中是否存在 CSV header