如何使用 pandas 和日期时间计算导入的 excel 列中重复日期的数量?

How do I count the number of repeated dates, using pandas & datetime, within an imported excel column?

我正在寻找一种可以将 count() 函数仅应用于特定日期范围的方法。我附上了我现在正在使用的代码。如您所见,我已经生成了我想要的特定日期范围,但我不确定如何将计数函数应用到这个范围,然后让它仍然生成一个图。

下面的数据样本只是其中的几列——有 16 列,但我只需要使用 date_report。

来自 excel 样本的数据:

'''

   sex---------country-------date_report

    M           Canada       03-01-2020

    F           Canada       03-01-2020

    M           Canada       03-02-2020

    F           Canada       03-02-2020

    M           Canada       03-02-2020

    M           Canada       03-03-2020

    F           Canada       03-03-2020

    M           Canada       03-04-2020

    F           Canada       03-04-2020

    M           Canada       03-04-2020

'''

我需要从 date_report 列计算 2020 年 3 月 1 日至 2020 年 7 月 10 日的病例数。 行中有重复的日期,需要将这些日期相加,因此每个日期有一个总值(2020 年 1 月 3 日为 2 个,2020 年 2 月 3 日为 4 个,依此类推)

读取 excel 文件并导入 pandas 和日期时间后:

'''

    day_first=datetime.date(2020, 3, 1)
    day_last=datetime.date(2020, 7, 10)
    delta = (day_last - day_first)
    print(delta.days)

    for i in range(delta.days + 1):
        all_dates = day_first + datetime.timedelta(+i)
        print(all_dates)    # This gives me the range of dates I am looking for. 

    date_count=df.groupby('date_report').date_report.count()

    print(date_count)

    date_count.plot(kind='line') # This plot goes from the first date in January until the end of the list, I just want March 1-July 10. 

'''

正如我所说,目标是在 x 轴上绘制 3 月 1 日至 7 月 10 日的线图,在 y 轴上显示每天的病例总数。 任何帮助将不胜感激!

您只需在执行 groupby 之前将初始数据集缩减为您感兴趣的日期:

import matplotlib.pyplot as plt

# select data between dates of interest
sub_df = df.loc[df['date_report'].between(first_day, last_day), :]

date_count = sub_df.groupby('date_report').date_report.count()

date_count.plot(kind='line')
plt.show()

如果您需要更改日期在数据框中的存储方式以解决各种类型(datetime.datetimedatetime64[ns])之间的兼容性问题,您可以将它们转换为通用的 pd.Timestamp 对象

df['date_report'] = [pd.Timestamp(d) for d in df['date_report']]

或者,在这种情况下,边界日期时间:

first_day = pd.Timestamp(first_day)
last_day = ...