检测Dandas系列DatetimeIndex中的连续日期

问题描述 投票:0回答:2

我有日期格式(YYYY-MM-DD)的pandas系列DatetimeIndex,并且想要标记连续区域,其中每个索引相对于一天是连续的 - 所以如果Datetime系列中有一个缺少的日期,我想检测它,即:

...
2005-01-15
2005-01-16
2005-01-17
2005-02-15
2005-02-16
...

2005-01-17和2005-02-15之间缺少天数的差距很明显。

用pandas找不到简单的方法,而我期待一些我不知道的辅助函数。更一般地说,也将赞赏numpy解决方案。


@smci,我不知道dput()是什么,但这里有一种生成样本数据的方法:

import pandas as pd
import numpy as np

data = pd.concat([
    pd.Series(np.random.randn(3), pd.date_range('2005-01-15', '2005-01-17')),
    pd.Series(np.random.randn(3), pd.date_range('2005-02-15', '2005-02-17'))
])
datetime numpy pandas date-arithmetic
2个回答
1
投票

尝试类似的东西:

data.index - data.index.shift(1, freq=pd.DateOffset(1))

per @ chrisb对Calculating time difference between two rows的回答


0
投票

问题是,Smci的答案对于检测缺失日期并不起作用。

我使用DataFrame.asfreq('D')来检测缺失值。将列出缺少的日期,但其对应的值将显示为NAN。例如:

df1 = df.asfreq('D)
missing_dates=df1[df1.Column.isnull()]
© www.soinside.com 2019 - 2024. All rights reserved.