【问题标题】:Find the cumulative number of missing days for a datetime column in pandas查找熊猫中日期时间列的累计缺失天数
【发布时间】:2021-11-21 16:12:04
【问题描述】:

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

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 

它的sn-p如下所示。 “日期”列采用日期时间格式。

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

ID      Missing days

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

B        1       (14th march missing)

非常感谢任何帮助。谢谢。

【问题讨论】:

  • 您需要付出一些努力来尝试解决问题,而不是期待免费的完整解决方案。你已经尝试过什么?

标签: python-3.x pandas dataframe datetime data-science


【解决方案1】:

下面的答案将因连续缺失多天而失败(感谢 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

【讨论】:

  • 你说得对,我会尝试修复@Ben.T
  • 新答案应该涵盖@Ben.T
  • 是的,很好。使用你原来的方法,在申请中我想出了lambda x: (x.dt.date.diff().dt.days-1).clip(lower=0).sum(),但我不认为它比重新采样更好!
  • 也不错,我用dt.date 太少了
  • 非常感谢你们俩。我已经坚持了一段时间。现在放心了。
猜你喜欢
  • 2018-04-24
  • 1970-01-01
  • 2021-09-18
  • 2018-08-17
  • 2019-09-12
  • 2019-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多