首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python查找时间在列表中不连续

Python查找时间在列表中不连续
EN

Stack Overflow用户
提问于 2019-08-09 00:56:25
回答 6查看 177关注 0票数 1

我有两个这样的df:

代码语言:javascript
复制
df1
x   y
0   64
1   57
2   51
3   46
4   
5   
6   35
7   
8   
9   29

df2
x   y
0   85
1   22
2   77
3   65
4   21
5   13
6   34
7   98
8   
9   29

我正在尝试找出每个列表中有多少个漏洞。在df1中,有两个洞,这意味着有两个点在连续数字中有一个断点。在df2中,有一个漏洞。

如果我像下面这样保存非空的x值,我就会得到一个数字列表。

代码语言:javascript
复制
df3 = df1.loc[~df1['y'].isnull()]
listcheck = df3['x'].tolist()

print(listcheck)
[0, 1, 2, 3, 6, 9]

我可以使用这个列表来找出上面描述的漏洞吗?

EN

回答 6

Stack Overflow用户

发布于 2019-08-09 01:26:34

你可以这样做:

代码语言:javascript
复制
num_holes = 0

# find hole at beginning of array
if listcheck[0] > 0:
    num_holes += 1

# find hole at end of array
if listcheck[-1] != len(df1)-1:
    num_holes += 1

# find hole in the middle of array
for i in range(len(listcheck) - 1):
    if listcheck[i+1] - listcheck[i] > 1:
        num_holes += 1

print(num_holes)
票数 2
EN

Stack Overflow用户

发布于 2019-08-09 01:04:16

您可以尝试:

代码语言:javascript
复制
holes = 0
for i, j in zip(listcheck[:-1], listcheck[1:]):
    if j - i > 1:
        holes += 1
print(holes)
# output: 2
票数 1
EN

Stack Overflow用户

发布于 2019-08-09 01:15:37

可能不是最好的方法,但这是我想到的第一件事:

代码语言:javascript
复制
tmp = [-1]+listcheck+len(df1)    # Add boundaries to see if first (0) and the last elements are also missing
holes = sum([1 for i in range(1, len(listcheck)+2) if tmp[i] != tmp[i-1]+1])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57417423

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档