我有两个这样的df:
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值,我就会得到一个数字列表。
df3 = df1.loc[~df1['y'].isnull()]
listcheck = df3['x'].tolist()
print(listcheck)
[0, 1, 2, 3, 6, 9]我可以使用这个列表来找出上面描述的漏洞吗?
发布于 2019-08-09 01:26:34
你可以这样做:
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)发布于 2019-08-09 01:04:16
您可以尝试:
holes = 0
for i, j in zip(listcheck[:-1], listcheck[1:]):
if j - i > 1:
holes += 1
print(holes)
# output: 2发布于 2019-08-09 01:15:37
可能不是最好的方法,但这是我想到的第一件事:
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])https://stackoverflow.com/questions/57417423
复制相似问题