【问题标题】:Get the count of the each date entry from onr of the raw from CSV file从 CSV 文件的某一行中获取每个日期条目的计数
【发布时间】:2016-05-11 06:01:12
【问题描述】:

我正在使用 python 从 CSV 文件中获取值并创建图表。 如何获取每个日期的条目数?例如,示例日期行:

4/14/2016  11:05:15 AM
4/14/2016  09:06:15 PM
6/14/2016  11:05:15 AM

它应该给出一个输出为

4/14/2016 entry 2 times
6/14/2016 entry 1 time

【问题讨论】:

    标签: python csv datetime


    【解决方案1】:

    你可以使用itertools.groupby:

    with open("your_file.csv") as f:
        for x,y in itertools.groupby(sorted(map(str.split, f.read().strip().split("\n"))), key = lambda x:x[0]):
            print x,len(list(y))
    

    输出

    4/14/2016 2
    6/14/2016 1
    

    另一种方式:如果 csv 包含空行

    with open("your_file.csv") as f:
        my_list = []
        for line in f:
            if line:
                my_list.append(line.strip().split())
        for x,y in itertools.groupby(sorted(my_list, key=lambda x:x[0]), key=lambda x:x[0]):
            print x, len(list(y))
    

    【讨论】:

    • 谢谢 :) 适用于少量(在 10 个条目上测试)的 csv 条目。但是对于下面的 150 个条目,给出错误“IndexError: list index out of range”for x,y in itertools.groupby(sorted(map(str.split, f.read().strip().split("\n"))), key = lambda x:x[0]):
    【解决方案2】:

    简单地计算日期:

    import csv
    from collections import Counter
    
    c = Counter()
    with open('somefile.csv') as f:
       reader = csv.reader(f, delimiter='\t')
       for row in reader:
          c.update(row[0])
    
    for date,count in c.most_common():
       print('{} {}'.format(date, count))
    

    【讨论】:

    • 你确定这有效吗?它给了我输出:/ 6 1 6 4 5 6 4 0 3 2 3
    • 如果您的 csv 格式如您所述,它将起作用;您需要根据文件中的内容调整分隔符。在我的示例中,分隔符是一个制表符\t
    • 我觉得还是不行,你应该把row[0]改成row[0:1]
    【解决方案3】:

    您可以使用defaultdict 来获取值以及计数:

    import collections
    
    d=collections.defaultdict(list)
    
    with open('data', 'r') as f:
        for line in map(lambda line:line.strip(), f.readlines()):
            row=line.split()
            d[row[0]].append(row[1])
    print(d)
    for key, value in d.items():
        print(key+' has the following '+str(len(value))+' entries/entry: '+str(value))
    

    输出:

    $ cat data 
    4/14/2016  11:05:15 AM
    4/14/2016  09:06:15 PM
    6/14/2016  11:05:15 AM
    $ python p.py 
    defaultdict(<type 'list'>, {'4/14/2016': ['11:05:15', '09:06:15'], '6/14/2016': ['11:05:15']})
    4/14/2016 has the following 2 entries/entry: ['11:05:15', '09:06:15']
    6/14/2016 has the following 1 entries/entry: ['11:05:15']
    

    【讨论】:

      猜你喜欢
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多