计算熊猫时间序列中的连续 nan 值

Counting continuous nan values in panda Time series

我实际上在 Python 3 和 Pandas 中处理时间序列,我想合成连续缺失值的时间段,但我只能找到 nan 值的索引...

Sample data :
                     Valeurs
2018-01-01 00:00:00      1.0
2018-01-01 04:00:00      NaN
2018-01-01 08:00:00      2.0
2018-01-01 12:00:00      NaN
2018-01-01 16:00:00      NaN
2018-01-01 20:00:00      5.0
2018-01-02 00:00:00      6.0
2018-01-02 04:00:00      7.0
2018-01-02 08:00:00      8.0
2018-01-02 12:00:00      9.0
2018-01-02 16:00:00      5.0
2018-01-02 20:00:00      NaN
2018-01-03 00:00:00      NaN
2018-01-03 04:00:00      NaN
2018-01-03 08:00:00      1.0
2018-01-03 12:00:00      2.0
2018-01-03 16:00:00      NaN

Expected results :
       Start_Date      number of contiguous missing values 
2018-01-01 04:00:00      1
2018-01-01 12:00:00      2
2018-01-02 20:00:00      3
2018-01-03 16:00:00      1

我如何通过 pandas (shift(), cumsum(), groupby() ???) 获得此类结果?

感谢您的指教!

西尔万

如果您有值出现的索引,则可以像 this 中那样使用 itertools 来查找连续块

groupbyagg

mask = df.Valeurs.isna()
d = df.index.to_series()[mask].groupby((~mask).cumsum()[mask]).agg(['first', 'size'])
d.rename(columns=dict(size='num of contig null', first='Start_Date')).reset_index(drop=True)

            Start_Date  num of contig null
0  2018-01-01 04:00:00                   1
1  2018-01-01 12:00:00                   2
2  2018-01-02 20:00:00                   3
3  2018-01-03 16:00:00                   1

处理基础 numpy 数组:

a = df.Valeurs.values
m = np.concatenate(([False],np.isnan(a),[False]))
idx = np.nonzero(m[1:] != m[:-1])[0]

out = df[df.Valeurs.isnull() & ~df.Valeurs.shift().isnull()].index

pd.DataFrame({'Start date': out, 'contiguous': (idx[1::2] - idx[::2])})

            Start date  contiguous
0  2018-01-01 04:00:00           1
1  2018-01-01 12:00:00           2
2  2018-01-02 20:00:00           3
3  2018-01-03 16:00:00           1