Pandas数据帧中连续NaN大于阈值

2024-10-06 12:08:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在Pandas数据帧中找到连续NaN的那些索引,其中超过3个连续NaN返回它们的大小。即:

58234         NaN
58235         NaN
58236    0.424323
58237    0.424323
58238         NaN
58239         NaN
58240         NaN
58241         NaN
58242         NaN
58245         NaN
58246    1.483380
58247    1.483380

应该返回类似(58238,6)的值。返回的实际格式并不重要。我发现了以下内容。在

^{pr2}$

但它没有为每个索引返回正确的值。这个问题可能非常类似于Identifying consecutive NaN's with pandas 但如果有人帮我,我会非常感激的,因为我在熊猫界是个十足的无赖。在


Tags: 数据pandas格式withnan我会identifyingpr2
3条回答

我把台阶弄坏了:

df['Group']=df.a.notnull().astype(int).cumsum()
df=df[df.a.isnull()]
df=df[df.Group.isin(df.Group.value_counts()[df.Group.value_counts()>3].index)]
df['count']=df.groupby('Group')['Group'].transform('size')
df.drop_duplicates(['Group'],keep='first')
Out[734]: 
        a  Group  count
ID                     
58238 NaN      2      6

所以这会有点慢,但我也是熊猫和Python的初学者。它是超级丑陋的,但不知道你的数据集我会怎么做。在

current_consec = 0
threeormore = 0

for i in dataset[whatever column you need]:
    if pd.isnull(i):
        if current_consec == 3:
            current_consec = 0
            threeormore += 1
        else:
            current_consec += 1
   else:
      current_consec = 0

因为它会在indx上运行,它会找到按顺序运行的每一个。唯一的问题是,如果你不想每次一行有三个(连续6次锯),你就必须修改一下代码,不把current consec更改为0,并创建一个pass语句。在

抱歉,这是一个新的答案,但它可能会工作,如果你找到更快的东西,让我知道,因为我很乐意将它添加到我的知识库。在

祝你好运

安迪M

假设df将这些列命名为两列:AB,这里有一种矢量化方法-

thresh = 3

a = df.A.values
b = df.B.values

idx0 = np.flatnonzero(np.r_[True, np.diff(np.isnan(b))!=0,True])
count = np.diff(idx0)
idx = idx0[:-1]
valid_mask = (count>=thresh) & np.isnan(b[idx])
out_idx = idx[valid_mask]
out_num = a[out_idx]
out_count = count[valid_mask]
out = zip(out_num, out_count)

样本输入,输出-

^{pr2}$

使用thresh = 2,我们有-

^{3}$

相关问题 更多 >