检查索引中是否有任何缺失的日期

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

有什么方法可以直接检查数据框中丢失的日期。 我想检查

2013-01-19
2018-01-29

之间是否缺少日期
            GWA_BTC      GWA_ETH    GWA_LTC  GWA_XLM  GWA_XRP
   Date                 
2013-01-19  11,826.36   1,068.45    195.00    0.51    1.82
2013-01-20  13,062.68   1,158.71    207.58    0.52    1.75
   ...
2018-01-28  12,326.23   1,108.90    197.36    0.48    1.55
2018-01-29  11,397.52   1,038.21    184.92    0.47    1.43

我尝试手动检查,但花了很多时间。

python pandas missing-data python-datetime
6个回答
84
投票

您可以使用DatetimeIndex.difference(其他)

pd.date_range(start = '2013-01-19', end = '2018-01-29' ).difference(df.index)

它返回其他元素中不存在的元素


4
投票

示例:

举个最简单的例子:

>>> df
              GWA_BTC   GWA_ETH  GWA_LTC  GWA_XLM  GWA_XRP
Date                                                      
2013-01-19  11,826.36  1,068.45   195.00     0.51     1.82
2013-01-20  13,062.68  1,158.71   207.58     0.52     1.75
2013-01-28  12,326.23  1,108.90   197.36     0.48     1.55
2013-01-29  11,397.52  1,038.21   184.92     0.47     1.43

我们可以找到

2013-01-19
2013-01-29

之间缺失的日期

方法一:

参见@Vaishali的回答

使用

.difference
查找日期时间索引与范围内所有日期集之间的差异:

pd.date_range('2013-01-19', '2013-01-29').difference(df.index)

返回:

DatetimeIndex(['2013-01-21', '2013-01-22', '2013-01-23', '2013-01-24',
               '2013-01-25', '2013-01-26', '2013-01-27'],
              dtype='datetime64[ns]', freq=None)

方法二:

您可以使用所需日期范围内的所有日期重新索引数据框,并找到

reindex
插入
NaN
的位置。

并查找

2013-01-19
2013-01-29
之间缺失的日期:

>>> df.reindex(pd.date_range('2013-01-19', '2013-01-29')).isnull().all(1)

2013-01-19    False
2013-01-20    False
2013-01-21     True
2013-01-22     True
2013-01-23     True
2013-01-24     True
2013-01-25     True
2013-01-26     True
2013-01-27     True
2013-01-28    False
2013-01-29    False
Freq: D, dtype: bool

带有

True
的值是原始数据框中缺失的日期


3
投票

您可以使用 DatetimeIndex.difference 并添加频率参数,这样您就可以根据您使用的频率检查丢失的天数、小时数、分钟数:

pd.date_range(df.index.min(), df.index.max(), freq="1min").difference(df.index)

2
投票

假设数据是每日非营业日期:

df.index.to_series().diff().dt.days > 1

0
投票

我无法发表评论,但你也许可以遍历每个值并将 24 小时添加到前一个值以查看日期是否匹配?

import pandas as pd

a = [1,2,3,4,5]
b = [1,0.4,0.3,0.5,0.2]

df = pd.DataFrame({'a':a , 'b': b})

for i in range(len(df)):
    prev = df.loc[i,'a']
    if i is 0:
        continue
    else:
         # Add 1 day to the current value and check with prev value

0
投票
pd.date_range(df.index.min(), df.index.max()).difference(df.index)
© www.soinside.com 2019 - 2024. All rights reserved.