在 pandas 中查找日期时间列的累计缺失天数

Find the cumulative number of missing days for a datetime column in pandas

我有一个示例数据框,如下所示。

import pandas as pd

data = {'ID':['A', 'A', 'A','A','A','A' ,'B','B','B','B','B'],
'Date':['2021-09-20 04:34:57', '2021-09-20 04:37:25', '2021-09-22 04:38:26', '2021-09-23 
        00:12:29','2021-09-22 11:20:58','2021-09-25 09:20:58','2021-03-11 21:20:00','2021-03- 
        11 21:25:00','2021-03-12 21:25:00', '2021-03-13 21:25:00', '2021-03-15 21:25:00']}
df1 = pd.DataFrame(data)
df1 

它的片段如下。 'Date' 列采用日期时间格式。

现在,我想找出每个参与者之间缺失日期的总数并打印它们(或创建一个新的数据框)。

ID      Missing days

A        3       (21st,22nd and 24th September dates missing)

B        1       (14th march missing)

非常感谢任何帮助。谢谢

下面的答案将因连续多天缺失而失败(感谢 Ben T)。我们可以通过每组使用 resample 来解决这个问题,而不是计算 NaT:

dfg = df1.groupby("ID").apply(lambda x: x.resample(rule="D", on="Date").first())
dfg["Date"].isna().sum(level=0).reset_index(name="Missing days")
  ID  Missing days
0  A             2
1  B             1

** 旧答案 **

我们可以使用 GroupBy.diff 并检查有多少差异大于 1 天:

df1["Date"] = pd.to_datetime(df1["Date"])
(
    df1.groupby("ID")["Date"]
    .apply(lambda x: x.diff().gt(pd.Timedelta(1, "D")).sum())
    .reset_index(name="Missing days")
)
  ID  Missing days
0  A             2
1  B             1