如果数据帧列中有两个连续的 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/