首页 > 解决方案 > 如何使用 python 在 pandas 中查找具有逻辑的索引?

问题描述

这是我的数据:

           time           id    w
0   2018-03-01 00:00:00 39.0    1176.000000
1   2018-03-01 00:15:00 39.0    NaN
2   2018-03-01 00:30:00 39.0    NaN
3   2018-03-01 00:45:00 39.0    NaN
4   2018-03-01 01:00:00 39.0    NaN
5   2018-03-01 01:15:00 39.0    NaN
6   2018-03-01 01:30:00 39.0    NaN
7   2018-03-01 01:45:00 39.0    1033.461538
8   2018-03-01 02:00:00 39.0    1081.066667
9   2018-03-01 02:15:00 39.0    1067.909091
10  2018-03-01 02:30:00 39.0    NaN
11  2018-03-01 02:45:00 39.0    1051.866667
12  2018-03-01 03:00:00 39.0    1127.000000
13  2018-03-01 03:15:00 39.0    1047.466667
14  2018-03-01 03:30:00 39.0    1037.533333

我想得到指数:10

因为我需要知道哪个时间不连续,我需要添加值。

我想知道每个“时间”前后是否有一个 NAN。如果不是,我需要知道它的索引。我需要为它增加价值。

我的数据非常大。我需要一个更快的方法。

我真的需要你的帮助。非常感谢。

标签: pythonpandas

解决方案


这应该工作得很快:

import numpy as np

index = np.array([4561,4723,4724,4725,4726,5154,5220,5221,5222,5223,5224,5293,5437,5484,5485,5486,5487])

continuous = np.diff(index) == 1
not_continuous = np.where(~continuous[1:] & ~continuous[:-1])[0] + 1 # check on both 'sides', +1 because you 'loose' one index in the diff operation
index[not_continuous]

array([5154, 5293, 5437])

它不能很好地处理第一个值,但这很模棱两可,因为您没有要检查的先前值。如果这对您很重要,您可以添加这个额外的检查......可能与最后一个值相同。


推荐阅读