简体   繁体   English

在Counter,Python中添加0计数值

[英]Adding 0 count values in Counter, Python

I have written a snippet that fetches ( dates )data from database and counts the occurrences of dates accordingly. 我编写了一个片段,该片段从数据库中获取( 日期 )数据并相应地计算日期的出现。 However since the data in the Db is not consistent some of the dates are not present.My code is Below: 但是,由于Db中的数据不一致,因此某些日期不存在。我的代码如下:

import MySQLdb
import sys
import matplotlib.pyplot as plt
from collections import Counter, OrderedDict

connection = MySQLdb.connect ()

cursor = connection.cursor ()

cursor.execute ()

#fetch all of the rows from the query
data = cursor.fetchall()
ddt =  sorted(set(data))

coll = Counter(data)
orddict = OrderedDict(sorted(coll.items()))# Sorts the dates in order
print orddict 

The output is here: 输出在这里:

在此处输入图片说明

Is there a way where I can get(print) the missing dates in between with count 0? 有没有一种方法可以获取(打印)计数0之间的缺失日期?

Edit 1 : I tried printing out a datelist in sequence however ,the code only prints today's date.The code is as follows: 编辑1:我尝试按顺序打印出一个日期列表 ,但是该代码仅打印今天的日期。代码如下:

def dert():
    d1 = date(2017, 07, 15)  # start date
    d2 = datetime.date.today()  # end date
    delta = d2 - d1         # timedelta 
    for i in range(delta.days + 1):
        x = (d1 + timedelta(days= i))
    return  x 
print dert()

It seems to me that you could create an additional list which will contain all dates in sequential order starting from the needed date/first date in db. 在我看来,您可以创建一个附加列表,该列表将包含从db中所需的日期/第一个日期开始的所有顺序的日期。

Now once you have the additional list you can run on the in checking for each if it is in the db, if in db print count, otherwise print 0 现在,有了附加列表后,就可以在in中运行检查每个列表是否在db中,是否在db中打印计数,否则打印0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM