【问题标题】:Count numbers from row in CSV file从 CSV 文件中的行计算数字
【发布时间】:2012-11-20 23:02:53
【问题描述】:

所以我有这个 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]

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

【问题讨论】:

  • 看起来不像 CSV 或实际上是 row - 是您的示例 实际 数据
  • homework 标签正在被移除,请勿使用。
  • @JonClements:我认为 OP 的意思是“一栏”。代码引用row[3]
  • 你的代码 sn-p 引用了[3](第四个),但你说的是一个特定的。根据您的示例输入给我们一个示例输出。

标签: python csv matplotlib


【解决方案1】:

只需创建一个从数字到计数的映射。 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

【讨论】:

  • counts = collections.Counter(row[3] for row in my_reader) 适合那些喜欢单线的人。
  • thnx 我使用了你的一个代码 :) 我唯一需要做的就是更改输出,以便我可以将它与 matplotlib 一起使用来创建图形。 matplotlib 只需要 ("1003", 1) 并且代码的输出是 '1003' : 1,。我用 replace() 改变了它
  • @DT22:使用counts.items()获取(key, count)的元组序列。
  • 虽然在使用 python 时这是一个很好的答案,但我认为对于使用scipy ecosystem 的人来说这不是一个很好的答案。使用 numpy/matplotlib/pandas ...您通常会使用返回数组的解析器(numpy.loadtxt、numpy.genfromtxt、pandas.read_csv)并尝试使用矢量化函数(在 python 标准库中不可用)。有时感觉科学 python 是一种完全不同的语言。
【解决方案2】:

您可以使用pandas 来读取数据、计算值并绘制它。 Pandas 在幕后使用numpymatplotlib 来实现这一点。 read_csv 和绘图命令也适用于多列。

In [29]: df = pd.read_csv('data.csv', names=['my_data']) 

In [30]: counts = df['my_data'].value_counts()

In [31]: counts
Out[31]: 
1022     3
1042     3
1040     3
1035     3
11728    3
1036     2

In [32]: counts.plot(kind='barh')
Out[32]: <matplotlib.axes.AxesSubplot at 0x4f7f510>

【讨论】:

    【解决方案3】:

    此代码将计算总行数,如果您想要特定行,则在打印语句之前使用 if 条件并检查 if count==row_number exa: if count==3: 并获取总数。

             reader=csv.reader(open("first.csv"))
             count=0;
             for row in reader:
                 count+=1
                 print "total no in row "+str(count)+" is "+str(len(row))
                 for i in row:
                     print i
    

    【讨论】:

      【解决方案4】:

      您可以使用简单的字典。

      my_reader = csv.reader(open(csvpath))
      my_dict = {}
      for row in my_reader:
          try:
              my_dict[row[3]] += 1
          except KeyError:
              my_dict[row[3]] = 0
      

      【讨论】:

        猜你喜欢
        • 2015-08-27
        • 1970-01-01
        • 1970-01-01
        • 2011-06-07
        • 1970-01-01
        • 2011-10-14
        • 2012-12-30
        • 2018-10-17
        • 1970-01-01
        相关资源
        最近更新 更多