python - 检测列中两个连续的空值

标签 python dataframe isnull

如果数据帧列中有两个连续的 Null 值,我想要一个返回 bool 值(False 或 True)的函数。

我尝试创建一个循环,对整个列进行迭代,如果在一行中找到两个空值,则返回 True。

def consec_null(df,i):
 j=0
 b=False
 while j<(len(df.index)-1):
  if ((pd.isnull(df.iloc[j,i])) and (pd.isnull(df.iloc[j+1,i]))):
   b=True
  else: 
   j=j+1   
 return b

此代码继续运行,不会显示任何结果或错误。

最佳答案

您可以使用.shift(-1) ,像这样:

import pandas as pd
import numpy as np


def consec_null(df, i):
    col = df[df.columns[i]]
    return (col.isnull() & col.shift(-1).isnull()).any()


df = pd.DataFrame.from_dict({"A": [1.0, np.nan, 3.0, np.nan, 5.0], "B": [1.0, 2.0, np.nan, np.nan, 5.0]})

print(consec_null(df, 0))
print(consec_null(df, 1))

输出:

False  # because A doesn't have 2 consecutive nulls
True   # because B has 2 consecutive nulls

关于python - 检测列中两个连续的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57148600/

相关文章:

python - Tensorflow Keras Input层没有添加_keras_shape

python - 如何在 Django Rest Framework 中使用手机号码登录。

SQL Server NULL 整数使用 ISNULL 转换为空字符串

python - pandas多索引直接排序

sql-server - 同一列 ISNULL 两次

SQL:具有不同类型参数的 ISNULL 函数

python - 模块加载在CPython中如何工作?

python - conda 创建-n 测试 pandas=0.12.0 (?)

python - 我如何使用 pandas 数据框,这样我只得到真实的行,如果条件不正确,我什么也得不到

python - Pandas 数据框 : get column item when the corresponding item in another column is greater than a value