Python查找列表中不连续的时间
我有两个类似这样的df:Python查找列表中不连续的时间,python,pandas,Python,Pandas,我有两个类似这样的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
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]
我可以使用此列表来计算上述孔吗?您可以尝试:
holes = 0
for i, j in zip(listcheck[:-1], listcheck[1:]):
if j - i > 1:
holes += 1
print(holes)
# output: 2
也许不是最好的方法,但这是我想到的第一件事:
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])
试试这个:
df = pd.DataFrame({'A' : [1,2,None,3, 4, None, None, 5]})
temp = df.isna()
counter = 0
isna = False
for i in range(len(df)):
if temp['A'].iloc[i]:
if isna == False:
counter += 1
isna = True
else:
isna = False
print(counter)
我想到的解决方案可能有点令人困惑,但在更大的数据帧上,它会非常快:
number_of_consecutive_gaps = np.sum(np.diff(df['x'][df['y'].isnull()]) > 1)
number_of_initial_gaps = 1 if df['x'][df['y'].isnull()].shape[0] > 0 else 0
number_of_gaps = number_of_consecutive_gaps + number_of_initial_gaps
然而,基本假设是
df['x']
增加了一个单位1
,如果不是这样,您可以用df.index
替换df['x']
,并确保索引连续上升,然后它仍能正常工作。您可以执行以下操作:
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)
您只需使用
shift
的mask.isna
和.notna
即可找到值从非NaN
更改为NaN
的位置,并计算真值
(df1.y.isna() & df1.y.notna().shift(fill_value=True)).value_counts()[True]
Out[1073]: 2
关于df2:
(df2.y.isna() & df2.y.notna().shift(fill_value=True)).value_counts()[True]
Out[1076]: 1
你好您能展示一些您尝试过的代码吗?@maxutil立即检查是否有效!谢谢你,鲁苏罗。我以后需要研究这个代码来找出它是如何工作的。这个代码是基于这样一个观察结果的:如果你的列表检查中有两个邻居的号码不是连续的,这意味着有一个holeThanks,我喜欢这个。非常简单,更符合我的能力:)仅供参考,如果您的数据帧缺少第一个或最后一个值,这将不会给您正确的结果。我对ita进行了修复,洞需要2个边距,因此初始代码很好,ofc取决于OP要求